def main(): def send_pkt(payload='', eof=False): return tb.txpath.send_pkt(payload, eof) parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-s", "--size", type="eng_float", default=400, help="set packet size [default=%default]") parser.add_option("-M", "--megabytes", type="eng_float", default=1.0, help="set megabytes to transmit [default=%default]") parser.add_option("","--discontinuous", action="store_true", default=False, help="enable discontinuous mode") parser.add_option("","--from-file", default=None, help="use intput file for packet contents") parser.add_option("","--to-file", default=None, help="Output file for modulated samples") transmit_path.add_options(parser, expert_grp) digital.ofdm_mod.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) (options, args) = parser.parse_args () # build the graph tb = my_top_block(options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() # start flow graph # generate and send packets nbytes = int(1e6 * options.megabytes) n = 0 pktno = 0 pkt_size = int(options.size) while n < nbytes: if options.from_file is None: # data = (pkt_size - 2) * (pktno & 0xff) data = (pkt_size - 2) * 'a' else: data = source_file.read(pkt_size - 2) if data == '': break; payload = struct.pack('!H', pktno & 0xffff) + data send_pkt(payload) n += len(payload) # sys.stderr.write('.') if options.discontinuous and pktno % 5 == 4: time.sleep(1) pktno += 1 # print pktno, ' ' print('payload = ', payload) send_pkt(eof=True) tb.wait() # wait for it to finish
def get_options(mods): parser = OptionParser(option_class=eng_option, conflict_handler="resolve") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='psk', help="Select modulation from: %s [default=%%default]" % (', '.join(mods.keys()),)) parser.add_option("", "--amplitude", type="eng_float", default=0.2, help="set Tx amplitude (0-1) (default=%default)") parser.add_option("-r", "--bitrate", type="eng_float", default=250e3, help="Select modulation bit rate (default=%default)") parser.add_option("-S", "--samples-per-symbol", type="float", default=2, help="set samples/symbol [default=%default]") parser.add_option("","--to-file", default=None, help="Output file for modulated samples") if not parser.has_option("--verbose"): parser.add_option("-v", "--verbose", action="store_true", default=False) if not parser.has_option("--log"): parser.add_option("", "--log", action="store_true", default=False) uhd_transmitter.add_options(parser) for mod in mods.values(): mod.add_options(parser) (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() sys.exit(1) return (options, args)
def parse_args(): # enable real time scheduling r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable real time scheduling" # parse parameters parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") expert_grp.add_option("-c", "--carrier_threshold", type="eng_float", default=meta_data.default_carrier_thredshold, help="set carrier detect threshold (dB) [default=%default]") parser.add_option("-i","--id", default=meta_data.default_id, help="id: check out meta_data.py also.") receive_path.add_options(parser, expert_grp) uhd_receiver.add_options(parser) digital.ofdm_demod.add_options(parser, expert_grp) transmit_path.add_options(parser, expert_grp) digital.ofdm_mod.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) (options, args) = parser.parse_args () if int(options.id) == meta_data.default_id: print int(options.id) sys.stderr.write("You must specify -i ID or --id ID\n") parser.print_help(sys.stderr) sys.exit(1) else: options.rx_freq = meta_data.channels_freq_table[meta_data.init_channel_num] * 1e9 options.tx_freq = meta_data.channels_freq_table[meta_data.init_channel_num] * 1e9 options.bandwidth = (meta_data.default_bandwidth * 10000000.0)/4 return options
def add_options(parser, expert): add_freq_option(parser) transmit_path.transmit_path.add_options(parser, expert) expert.add_option("", "--tx-freq", type="eng_float", default=None, help="set transmit frequency to FREQ [default=%default]", metavar="FREQ") parser.add_option("-v", "--verbose", action="store_true", default=False) uhd_transmitter.add_options(parser) parser.add_option("", "--log", action="store_true", default=False,help="Log all parts of flow graph to file (CAUTION: lots of data)")
def main(): parser = OptionParser(conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") tx_top_block.add_options(parser) transmit_path.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) (options, args) = parser.parse_args() if options.cfg is not None: (options,args) = parser.parse_args(files=[options.cfg]) print "Using configuration file %s" % ( options.cfg ) tb = tx_top_block(options) if options.dot_graph: # write a dot graph of the flowgraph to file dot_str = tb.dot_graph() file_str = os.path.expanduser('tx_ofdm.dot') dot_file = open(file_str,'w') dot_file.write(dot_str) dot_file.close() try: tb.run() except [[KeyboardInterrupt]]: pass
def main(): parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-b", "--burst-length", type="int", default=50, help="Number of packets in each burst") parser.add_option("-t", "--sleep-time", type="int", default=100, help="sleep time (msec) between the bursts") parser.add_option("-s", "--server", type="string", default='idb2', help="server hosting the packet server/sink") parser.add_option("-o", "--port", type="int", default='5123', help="tcp port on the packet server/sink serving packets") parser.add_option("","--to-file", default=None, help="Output file for modulated samples") uhd_transmitter.add_options(parser) (options, args) = parser.parse_args () if len(args) != 0: parser.print_help() sys.exit(1) # build the graph tb = my_top_block(options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() # start flow graph tb.wait() # wait for it to finish
def main(): source_file = open("sample_audio", 'r') def send_pkt(payload='', eof=False): (no,) = (struct.unpack('!H', payload[0:2])) print "sending packet %4d " % (no) return tb.txpath.send_pkt(payload, eof) def rx_callback(ok, payload): (no,) = (struct.unpack('!H', payload[0:2])) print "ok = %5s pktno = %4d " % ( ok, no) mods = digital.modulation_utils.type_1_mods() demods = digital.modulation_utils.type_1_demods() # Create Options Parser: parser = OptionParser (option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='psk', help="Select modulation from: %s [default=%%default]" % (', '.join(mods.keys()),)) parser.add_option("-s", "--size", type="eng_float", default=1500, help="set packet size [default=%default]") transmit_path.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) receive_path.add_options(parser, expert_grp) uhd_receiver.add_options(parser) for mod in mods.values(): mod.add_options(expert_grp) for mod in demods.values(): mod.add_options(expert_grp) (options, args) = parser.parse_args () tb = my_top_block(mods[options.modulation], demods[options.modulation], rx_callback, options) pkt_size = int(options.size) data = source_file.read(pkt_size - 2) sequence_no = 0 tb.start() while data != '': payload = struct.pack('!H', sequence_no & 0xffff) + data send_pkt(payload) data = source_file.read(pkt_size - 2) sequence_no += 1 send_pkt(eof=True) tb.wait()
def main(): def send_pkt(payload='', eof=False, timeValid=False, timestamp=0): if eof: msg = gr.message(1) else: msg = gr.message_from_string(payload) if timeValid: secs = long(timestamp) frac_secs = timestamp - long(timestamp) msg.set_timestamp(secs, frac_secs) return tb.txpath.msgq().insert_tail(msg) parser = OptionParser(option_class=eng_option, conflict_handler="resolve") parser.add_option("-n", "--num", type="eng_float", default=1, help="set number of packets [default=%default]") parser.add_option("","--data-file", default=None, help="use complex input file for transmission") parser.add_option("","--to-file", default=None, help="Output file for modulated samples") parser.add_option("-W", "--bandwidth", type="eng_float", default=4e6, help="set symbol bandwidth [default=%default]") parser.add_option("", "--amp", type="eng_float", default=1, help="set gain factor for complex baseband floats [default=%default]") #transmit_path.add_options(parser, expert_grp) #digital.ofdm_mod.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) (options, args) = parser.parse_args () # build the graph tb = my_top_block(options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() # start flow graph ########################################################################### if options.data_file is None: sys.stderr.write("You must specify data file\n") parser.print_help(sys.stderr) sys.exit(1) print "End of Tx ..." time.sleep(1) ########################################################################### tb.wait() # wait for it to finish
def add_options(normal, expert): """ Adds usrp-specific options to the Options Parser """ normal.add_option("", "--outfile", type="string", help="select output file to modulate to") normal.add_option ("-c", "--channel", type="eng_float", default=17, help="Set 802.15.4 Channel to listen on channel %default", metavar="FREQ") normal.add_option("", "--amp", type="eng_float", default=1, metavar="AMPL", help="set transmitter digital amplifier: [default=%default]") normal.add_option("-v", "--verbose", action="store_true", default=False) normal.add_option("-W", "--bandwidth", type="eng_float", default=4000e3, help="set symbol bandwidth [default=%default]") expert.add_option("", "--log", action="store_true", default=False, help="Log all parts of flow graph to files (CAUTION: lots of data)") uhd_transmitter.add_options(normal)
def add_options(normal, expert): """ Adds usrp-specific options to the Options Parser """ uhd_transmitter.add_options(normal) add_freq_option(normal) normal.add_option("-T", "--tx-subdev-spec", type="subdev", default=None, help="select USRP Tx side A or B") normal.add_option("-v", "--verbose", action="store_true", default=False) # linklab, add options to specify which USRP to sue normal.add_option("-w", "--which", type="int", default=0, help="select which USRP (0, 1, ...) default is %default", metavar="NUM") expert.add_option("", "--tx-freq", type="eng_float", default=None, help="set transmit frequency to FREQ [default=%default]", metavar="FREQ") expert.add_option("-i", "--interp", type="intx", default=256, help="set fpga interpolation rate to INTERP [default=%default]")
def add_options(normal, expert_grp, channel_grp): mods = digital.modulation_utils.type_1_mods() for mod in mods.values(): mod.add_options(expert_grp) usrp_options.add_options(normal,expert_grp) uhd_transmitter.add_options(expert_grp) uhd_receiver.add_options(expert_grp) transmit_path.add_options(normal,expert_grp) receive_path.add_options(normal,expert_grp) channel_emulator.add_options(normal,channel_grp) expert_grp.add_option("","--use-whitener-offset", action="store_true", default=False, help="make sequential packets use different whitening") expert_grp.add_option("","--down-sample-rate", type="intx", default=1, help="Select the software down-sampling rate [default=%default]")
def main(): def send_pkt(payload='', eof=False): return tb.txpath.send_pkt(payload, eof) parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-s", "--size", type="eng_float", default=400, help="set packet size [default=%default]") transmit_path.add_options(parser, expert_grp) digital.ofdm_mod.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) (options, args) = parser.parse_args () # build the graph tb = my_top_block(options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() # start flow graph # generate and send packets pktno = 0 pkt_size = int(options.size) while pktno < 200: pktno += 1 data = (pkt_size - 2) * chr(pktno & 0xff) payload = struct.pack('!H', pktno & 0xffff) + data send_pkt(payload) sys.stderr.write('.') time.sleep(1) send_pkt(eof=True) tb.wait() # wait for it to finish
def main(): parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") uhd_transmitter.add_options(parser) uhd_receiver.add_options(parser) (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() sys.exit(1) # build the graph tb = my_top_block(options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.run()
def main(): # Create Options Parser: parser = OptionParser (option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") uhd_receiver.add_options(parser) uhd_transmitter.add_options(parser) (options, args) = parser.parse_args () if len(args) != 0: parser.print_help(sys.stderr) sys.exit(1) # build the graph tb = my_top_block(options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: Failed to enable realtime scheduling." tb.start() # start flow graph tb.wait() # wait for it to finish
def add_options(normal, expert): """ Adds usrp-specific options to the Options Parser """ normal.add_option("", "--infile", type="string", help="select input file to TX from") normal.add_option("", "--outfile", type="string", help="select output file to modulate to") normal.add_option("", "--txdata", type="string", help="select data file") normal.add_option("", "--char", type="eng_float", default=0, metavar="CAMPL", help="input is char file that should be scaled by CAMPL/128: [default=%default]") normal.add_option("", "--amp", type="eng_float", default=1, metavar="AMPL", help="set transmitter digital amplifier: [default=%default]") normal.add_option("-v", "--verbose", action="store_true", default=False) normal.add_option("", "--repeat", action="store_true", default=False) normal.add_option("-W", "--bandwidth", type="eng_float", default=500e3, help="set symbol bandwidth [default=%default]") expert.add_option("", "--log", action="store_true", default=False, help="Log all parts of flow graph to files (CAUTION: lots of data)") uhd_transmitter.add_options(normal) ofdm_rxtx.TX.add_options(normal, expert) ofdm_rxtx.sender_thread.add_options(normal)
def main(): mods = digital.modulation_utils.type_1_mods() demods = digital.modulation_utils.type_1_demods() parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='bpsk', help="Select modulation from: %s [default=%%default]" % (', '.join(mods.keys()),)) parser.add_option("-s", "--size", type="eng_float", default=100, help="set packet size [default=%default]") parser.add_option("-M", "--megabytes", type="eng_float", default=1.0, help="set megabytes to transmit [default=%default]") parser.add_option("","--discontinuous", action="store_true", default=False, help="enable discontinous transmission (bursts of 5 packets)") parser.add_option("","--from-file", default=None, help="use intput file for packet contents") parser.add_option("","--to-file", default=None, help="Output file for modulated samples") parser.add_option("", "--mac", default=None , help = "MAC addres") parser.add_option("", "--version", default='6' , help = "gnuradio version, default 6 (3.6)") parser.add_option("", "--mac_dst", default=None , help = "Destination MAC addres") tp36.add_options(parser, expert_grp) tp37.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) rp36.add_options(parser, expert_grp) rp37.add_options(parser, expert_grp) uhd_receiver.add_options(parser) for mod in demods.values(): mod.add_options(expert_grp) for mod in mods.values(): mod.add_options(expert_grp) (options, args) = parser.parse_args () if len(args) != 0: parser.print_help() sys.exit(1) if options.from_file is not None: source_file = open(options.from_file, 'r') r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" q_tx =Queue.Queue(10) q_rx =Queue.Queue(10) l1=StartL1(q_rx,q_tx,options,mods[options.modulation],demods[options.modulation]) l1.start() schL1_L2= StartSchedL1_L2(q_rx,q_tx,options.mac) schL1_L2.start() # POR AHORA NO USO CAPA MAC # l2Mgmt=StartL2Mgmt(schL1_L2.mgmt_q1,schL1_L2.tx_ev_q,options.mac,"256","Red IIE") # l2Mgmt.start() l3= schedLayer3.Layer3(schL1_L2.tx_ev_q,schL1_L2.data_q,'/dev/net/tun',options.mac,options.mac_dst) c = raw_input('Press #z to end, or #w to test commands :') while c != "#z": c = raw_input('Press #z to end, or #w to test commands :') print "Program ends" l3.stop() schL1_L2.stop() l1.stop() #POR AHORA NO ESTOY USANDO CAPA 2 # l2.stop() exit(0)
def main(): def send_pkt(payload='', eof=False): return tb.txpath.send_pkt(payload, eof) global n_rcvd, n_right n_rcvd = 0 n_right = 0 def rx_callback(ok, payload): global n_rcvd, n_right (pktno,) = struct.unpack('!H', payload[0:2]) n_rcvd += 1 if ok: n_right += 1 #print "ok = %5s pktno = %4d n_rcvd = %4d n_right = %4d" % ( # ok, pktno, n_rcvd, n_right) mods = digital.modulation_utils.type_1_mods() demods = digital.modulation_utils.type_1_demods() parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='psk', help="Select modulation from: %s [default=%%default]" % (', '.join(mods.keys()),)) parser.add_option("-s", "--size", type="eng_float", default=1500, help="set packet size [default=%default]") parser.add_option("-M", "--megabytes", type="eng_float", default=1.0, help="set megabytes to transmit [default=%default]") parser.add_option("","--discontinuous", action="store_true", default=False, help="enable discontinous transmission (bursts of 5 packets)") parser.add_option("","--from-file", default=None, help="use intput file for packet contents") parser.add_option("","--to-file", default=None, help="Output file for modulated samples") transmit_path.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) for mod in mods.values(): mod.add_options(expert_grp) (options, args) = parser.parse_args () if len(args) != 0: parser.print_help() sys.exit(1) if options.from_file is not None: source_file = open(options.from_file, 'r') # build the graph tb = my_top_block(mods[options.modulation], demods[options.modulation], rx_callback, options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() # start flow graph #t = threading.Thread(target=dowork, args=(), name='worker') #t.start() # generate and send packets nbytes = int(1e6 * options.megabytes) n = 0 sense_n=1 pktno = 0 pkt_size = int(options.size) while n < nbytes: if pktno%1000 == 0 and sense_n==1: #sence once #time.sleep(1) #tb.txgate.set_enabled(True) #time.sleep(.01) #tb.sensegate.set_enabled(True) #t #avail_subc_bin = tb.sensepath.GetAvailableSpectrum() #avail_subc_str = subc_bin2str(avail_subc_bin) # print avail_subc_bin fftout=tb.sensepath.FFTresult() #fftout=tb.sensepath.GetPSD() sense_n=0 #tb.txgate.set_enabled(True) #tb.sensegate.set_enabled(False) else: # linklab, loop to empty the lower layer buffers to avoid detecting old signals #send_pkt(eof=False) sense_n=1 #tb.txgate.set_enabled(True) #t #time.sleep(.01) #tb.sensegate.set_enabled(False) #time.sleep(0.001) if bandchoose == 0: if options.from_file is None: data = (pkt_size - 2) * chr(pktno & 0xff) else: data = source_file.read(pkt_size - 2) if data == '': break; payload1 = struct.pack('!H', pktno & 0xffff) + data send_pkt1(payload1) n += len(payload1) sys.stderr.write('.') pktno += 1 elif bandchoose == 1: if options.from_file is None: data = (pkt_size - 2) * chr(pktno & 0xff) else: data = source_file.read(pkt_size - 2) if data == '': break; payload2 = struct.pack('!H', pktno & 0xffff) + data send_pkt2(payload2) n += len(payload2) sys.stderr.write('.') pktno += 1 else if options.from_file is None: data = (pkt_size - 2) * chr(pktno & 0xff) else: data = source_file.read(pkt_size - 2) if data == '': break; payload1 = struct.pack('!H', pktno & 0xffff) + data send_pkt1(payload1) n += len(payload1) sys.stderr.write('.') pktno += 1 if options.from_file is None: data = (pkt_size - 2) * chr(pktno & 0xff) else: data = source_file.read(pkt_size - 2) if data == '': break; payload2 = struct.pack('!H', pktno & 0xffff) + data send_pkt2(payload2) n += len(payload2) sys.stderr.write('.') pktno += 1 if options.discontinuous and pktno % 5 == 4: time.sleep(1) pktno += 1 send_pkt(eof=True) tb.wait() # wait for it to finish
def main(): def send_pkt(payload='', eof=False): return tb.txpath.send_pkt(payload, eof) parser = OptionParser(option_class=eng_option, conflict_handler="resolve") # add general parser option parser.add_option("","--from-file", default=None, help="use intput file for packet contents") parser.add_option("","--to-file", default=None, help="Output file for modulated samples") parser.add_option("-s","--swapIQ", action="store_true", default=False, help="swap IQ components before sending to USRP2 sink [default=%default]") parser.add_option("-v", "--verbose", action="store_true", default=False) parser.add_option("-l", "--log", action="store_true", default=False, help="write debug-output of individual blocks to disk") parser.add_option("-W", "--bandwidth", type="eng_float", default=500e3, help="set symbol bandwidth [default=%default]\ 20e6 -> 802.11a/g, OFDM-symbolduration=4us, \ 10e6 -> 802.11p, OFDM-symbolduration=8us") parser.add_option("", "--regime", type="string", default="1", help="set OFDM coderegime: [default=%default]\ 1 -> 6 (3) Mbit/s (BPSK r=0.5), \ 2 -> 9 (4.5) Mbit/s (BPSK r=0.75), \ 3 -> 12 (6) Mbit/s (QPSK r=0.5), \ 4 -> 18 (9) Mbit/s (QPSK r=0.75), \ 5 -> 24 (12) Mbit/s (QAM16 r=0.5), \ 6 -> 36 (18) Mbit/s (QAM16 r=0.75), \ 7 -> 48 (24) Mbit/s (QAM64 r=0.66), \ 8 -> 54 (27) Mbit/s (QAM64 r=0.75)") parser.add_option("", "--tx-amplitude", type="eng_float", default=0.3 , help="set gain factor for complex baseband floats [default=%default]") parser.add_option("-N", "--num", type="int", default=1 , help="set number of packets to send, [default=%default] ") parser.add_option("-r", "--repeat", type="int", default=1 , help="set number of HelloWorld in single packet to send, [default=%default] ") parser.add_option("-p", "--payload", type="string", default=None, help="payload ASCII-string to send, [default=%default]") parser.add_option("-R", "--role", type="string", default=None, help="payload ASCII-string to send, [default=%default]") uhd_transmitter.add_options(parser) (options, args) = parser.parse_args () if options.role == 'A': options.payload = "HelloWorld"*options.repeat elif options.role == 'B': options.payload = "WorldHello"*options.repeat else: options.payload = "HelloWorld"*options.repeat # This is the ASCII encoded message that will be put into the MSDU (you have to build IP headers on your own if you need them!) # Use monitor (promiscuous) mode on the receiver side to see this kind of non-IP frame. my_msg = options.payload # build the graph tb = my_top_block(options, my_msg) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" # start flow graph tb.start() if(options.from_file is None): # send frame counter = 0 while counter < options.num: send_pkt(my_msg , eof = False) counter = counter + 1 print "End of Transmission" send_pkt(eof = True) # wait for it to finish tb.wait()
def main(): mods = digital.modulation_utils.type_1_mods() demods = digital.modulation_utils.type_1_demods() parser = OptionParser (option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='gmsk', help="Select modulation from: %s [default=%%default]" % (', '.join(mods.keys()),)) parser.add_option("-s", "--size", type="eng_float", default=1500, help="set packet size [default=%default]") parser.add_option("-v","--verbose", action="store_true", default=False) parser.add_option("-p", "--PLR", type="intx", default=3, help="set packet loss rate [default=%default]") parser.add_option("-T", "--packLen", type="intx", default=200, help="set source symbol numbers [default=%default]") expert_grp.add_option("-c", "--carrier-threshold", type="eng_float", default=30, help="set carrier detect threshold (dB) [default=%default]") expert_grp.add_option("","--tun-device-filename", default="/dev/net/tun", help="path to tun device file [default=%default]") transmit_path.add_options(parser, expert_grp) receive_path.add_options(parser, expert_grp) uhd_receiver.add_options(parser) uhd_transmitter.add_options(parser) for mod in mods.values(): mod.add_options(expert_grp) for demod in demods.values(): demod.add_options(expert_grp) (options, args) = parser.parse_args () if len(args) != 0: parser.print_help(sys.stderr) sys.exit(1) # open the TUN/TAP interface #(tun_fd, tun_ifname) = open_tun_interface(options.tun_device_filename) if options.rx_freq is None or options.tx_freq is None: sys.stderr.write("You must specify -f FREQ or --freq FREQ\n") parser.print_help(sys.stderr) sys.exit(1) # Attempt to enable realtime scheduling r = gr.enable_realtime_scheduling() if r == gr.RT_OK: realtime = True else: realtime = False print "Note: failed to enable realtime scheduling" # instantiate the MAC #mac = cs_mac(tun_fd, verbose=True) mac = cs_mac(verbose=True) # build the graph (PHY) tb = my_top_block(mods[options.modulation], demods[options.modulation], mac.phy_rx_callback, options) mac.set_top_block(tb) # give the MAC a handle for the PHY if tb.txpath.bitrate() != tb.rxpath.bitrate(): print "WARNING: Transmit bitrate = %sb/sec, Receive bitrate = %sb/sec" % ( eng_notation.num_to_str(tb.txpath.bitrate()), eng_notation.num_to_str(tb.rxpath.bitrate())) print "modulation: %s" % (options.modulation,) print "freq: %s" % (eng_notation.num_to_str(options.tx_freq)) print "bitrate: %sb/sec" % (eng_notation.num_to_str(tb.txpath.bitrate()),) print "samples/symbol: %3d" % (tb.txpath.samples_per_symbol(),) tb.rxpath.set_carrier_threshold(options.carrier_threshold) print "Carrier sense threshold:", options.carrier_threshold, "dB" source_file = open('./foreman_cif.264', 'r') #print 'zhifeng: from file' #print 'source_file = ', source_file file_data = source_file.read() file_length = len(file_data) #print "file length is", file_length #print file_data #raw_input('zhifeng on 070928: press any key to continue') source_file.close() tb.start() # Start executing the flow graph (runs in separate threads) #K = 100 print "PLR: %s" % (options.PLR,) mac.main_loop(file_data, options.packLen, options.PLR) # don't expect this to return... tb.stop() # but if it does, tell flow graph to stop. tb.wait() # wait for it to finish
def main(): def send_pkt(payload='', eof=False): return tb.txpath.send_pkt(payload, eof) global n_rcvd, n_right n_rcvd = 0 n_right = 0 def rx_callback(ok, payload): global n_rcvd, n_right n_rcvd += 1 (pktno, ) = struct.unpack('!H', payload[0:2]) if ok: n_right += 1 print "ok: %r \t pktno: %d \t n_rcvd: %d \t n_right: %d" % ( ok, pktno, n_rcvd, n_right) if 0: printlst = list() for x in payload[2:]: t = hex(ord(x)).replace('0x', '') if (len(t) == 1): t = '0' + t printlst.append(t) printable = ''.join(printlst) print printable print "\n" parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("", "--discontinuous", action="store_true", default=False, help="enable discontinuous") parser.add_option("", "--from-file", default=None, help="input file of samples to demod") parser.add_option("-M", "--megabytes", type="eng_float", default=1.0, help="set megabytes to transmit [default=%default]") parser.add_option("-s", "--size", type="eng_float", default=400, help="set packet size [default=%default]") parser.add_option("-p", "--packno", type="eng_float", default=0, help="set packet number [default=%default]") transmit_path.add_options(parser, expert_grp) digital.ofdm_mod.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) receive_path.add_options(parser, expert_grp) uhd_receiver.add_options(parser) digital.ofdm_demod.add_options(parser, expert_grp) (options, args) = parser.parse_args() if options.from_file is None: if options.rx_freq is None: sys.stderr.write("You must specify -f FREQ or --freq FREQ\n") parser.print_help(sys.stderr) sys.exit(1) if options.packno is not None: packno_delta = options.packno print "assign pktno start: %d" % packno_delta # build the graph tb = my_top_block(rx_callback, options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() # start flow graph # generate and send packets nbytes = int(1e6 * options.megabytes) n = 0 pktno = 0 pkt_size = int(options.size) while n < nbytes: if options.from_file is None: data = (pkt_size - 2) * chr(pktno & 0xff) else: data = source_file.read(pkt_size - 2) if data == '': break payload = struct.pack('!H', (pktno + int(packno_delta)) & 0xffff) + data send_pkt(payload) n += len(payload) sys.stderr.write('.') if options.discontinuous and pktno % 5 == 4: time.sleep(1) pktno += 1 send_pkt(eof=True) time.sleep(2) # allow time for queued packets to be sent tb.wait() # wait for it to finish
def main(): def send_pkt(payload='', eof=False): return tb.txpath.send_pkt(payload, eof) mods = digital.modulation_utils.type_1_mods() parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='psk', help="Select modulation from: %s [default=%%default]" % (', '.join(mods.keys()), )) parser.add_option("-s", "--size", type="eng_float", default=1500, help="set packet size [default=%default]") parser.add_option("-M", "--megabytes", type="eng_float", default=1.0, help="set megabytes to transmit [default=%default]") parser.add_option( "", "--discontinuous", action="store_true", default=False, help="enable discontinous transmission (bursts of 5 packets)") parser.add_option("", "--from-file", default=None, help="use intput file for packet contents") parser.add_option("", "--to-file", default=None, help="Output file for modulated samples") transmit_path.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) for mod in mods.values(): mod.add_options(expert_grp) (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() sys.exit(1) if options.from_file is not None: source_file = open(options.from_file, 'r') # build the graph tb = my_top_block(mods[options.modulation], options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() # start flow graph # generate and send packets nbytes = int(1e6 * options.megabytes) n = 0 pktno = 0 # pkt_size = int(options.size) # randomly generated sequence for consistent packet generation rand_vec = [ 40, 238, 143, 75, 140, 206, 136, 82, 195, 147, 132, 207, 74, 240, 137, 28, 181, 23, 104, 149, 215, 142, 237, 159, 160, 145, 53, 71, 218, 218, 236, 244, 250, 225, 99, 89, 144, 236, 140, 10, 66, 64, 25, 60, 4, 131, 63, 212, 11, 219, 144, 118, 178, 237, 124, 203, 33, 74, 134, 201, 152, 52, 60, 6, 199, 27, 244, 46, 79, 29, 55, 83, 112, 118, 44, 213, 18, 67, 199, 28, 114, 229, 218, 138, 29, 156, 107, 25, 12, 198, 234, 129, 26, 128, 103, 158, 168, 60, 86, 169 ] # start of packet construction logic while n < nbytes: if options.from_file is None: # random packet traffic overrides options pkt_size = 16 * rand_vec[pktno % 100] data = (pkt_size - 2) * chr(pktno & 0xff) else: data = source_file.read(pkt_size - 2) if data == '': break payload = struct.pack('!H', pktno & 0xffff) + data send_pkt(payload) print(pkt_size) n += len(payload) sys.stderr.write('.') if options.discontinuous and pktno % 5 == 4: time.sleep(1) pktno += 1 # added by memcmanu 3/3/2020 print(pktno) # end of packet construction logic send_pkt(eof=True) tb.wait() # wait for it to finish
def main(): global n_rcvd, n_right, timestamp_len, virtual_frame n_rcvd = 0 n_right = 0 timestamp_len = 14 #26 # len(now) max_pkt = 200 wrong_pktno = 0xFF00 seed_len = 20 virtual_frame = '00000000' vf_len = 8 def get_random_seed(): seed = '{0:20}'.format(randint(1, 99999999999999999999)) # replace prefix spaces with 0, if any return seed.replace(' ', '0') def send_beacon_pkt(my_tb, pkt_amount): pktno = 0 # 0 as beacon for i in range(pkt_amount): payload_prefix = struct.pack('!H', pktno & 0xffff) data_size = len(payload_prefix) + timestamp_len print "data_size {}".format(data_size) dummy_data = (pkt_amount - data_size) * chr(pktno & 0xff) # now = str(datetime.now()) now_timestamp_str = '{:.3f}'.format(time.time()) payload = payload_prefix + now_timestamp_str + dummy_data my_tb.txpath.send_pkt(payload) # sys.stderr.write('.') print "{} send beacon signal {}...".format(str(datetime.now()), i) time.sleep(0.001) time.sleep(0.005) def send_beacon_pkt2(my_tb, pkt_amount, i): pktno = 0 # as beacon payload_prefix = struct.pack('!H', pktno & 0xffff) data_size = len(payload_prefix) + timestamp_len dummy_data = (pkt_amount - data_size) * chr(pktno & 0xff) now_timestamp_str = '{:.3f}'.format(time.time()) payload = payload_prefix + now_timestamp_str + dummy_data my_tb.txpath.send_pkt(payload) # sys.stderr.write('.') print "{} send beacon signal {}...".format(str(datetime.now()), i) def do_every(interval, send_pkt_func, my_tb, pkt_amt, iterations=1): # For other functions to check these variables global my_thread, my_iterations my_iterations = iterations if iterations < pkt_amt: # my_thread = threading.Timer(interval, do_every, # [interval, send_pkt_func, my_tb, pkt_amt, 0 # if iterations == 0 else iterations + 1]) my_thread = threading.Timer(interval, do_every, [interval, send_pkt_func, my_tb, pkt_amt, pkt_amt if iterations >= pkt_amt else iterations + 1]) #print "start thread" my_thread.start() # execute func send_pkt_func(my_tb, pkt_amt, iterations) # def send_init_pkt(my_tb, pkt_amount): # pktno = 1 # while pktno < pkt_amount: # if stop_init_pkt: # print "init interrupted!!!" # break # # payload_prefix = struct.pack('!H', pktno & 0xffff) # rand_seed = get_random_seed() # data_size = len(payload_prefix) + timestamp_len + len(rand_seed) + len(virtual_frame) # dummy_data = (pkt_amount - data_size) * chr(pktno & 0xff) # # now = str(datetime.now()) # now_timestamp_str = '{:.3f}'.format(time.time()) # payload = payload_prefix + now_timestamp_str + rand_seed + virtual_frame + dummy_data # my_tb.txpath.send_pkt(payload) # # sys.stderr.write('.') # print "{} init pktno {}".format(str(datetime.now()), pktno) # pktno += 1 # time.sleep(0.001) # # print "sleep 2 seconds" # time.sleep(0.005) def send_init_pkt2(my_tb, pkt_amount, pktno=1): global stop_init_pkt if stop_init_pkt: print "init interrupted!!!" my_thread.cancel() return payload_prefix = struct.pack('!H', pktno & 0xffff) rand_seed = get_random_seed() data_size = len(payload_prefix) + timestamp_len + len(rand_seed) + len(virtual_frame) dummy_data = (pkt_amount - data_size) * chr(pktno & 0xff) # now = str(datetime.now()) now_timestamp_str = '{:.3f}'.format(time.time()) payload = payload_prefix + now_timestamp_str + rand_seed + virtual_frame + dummy_data my_tb.txpath.send_pkt(payload) # sys.stderr.write('.') print "{} init pktno {}".format(str(datetime.now()), pktno) # @time_sync(10) # def send_ack_pkt(my_tb, temp_list): # while temp_list: # pktno, time_data, seed, virtual_frame = temp_list.pop(0) # ack_pktno = pktno # payload_prefix = struct.pack('!H', ack_pktno & 0xffff) # data_size = len(payload_prefix) + timestamp_len + len(seed) + len(virtual_frame) # dummy_data = (pkt_amt - data_size) * chr(ack_pktno & 0xff) # now_timestamp_str = '{:.3f}'.format(time.time()) # payload = payload_prefix + now_timestamp_str + seed + virtual_frame + dummy_data # my_tb.txpath.send_pkt(payload) # #sys.stderr.write('.') # time_data_str = str(datetime.fromtimestamp(time_data)) # print "Ack pktno {}, time {}, ack_pktno {}, seed {}, vf {}".format(pktno, time_data_str, ack_pktno, seed, virtual_frame) # time.sleep(0.001) # #my_tb.txpath.send_pkt(eof=True) # time.sleep(0.005) def send_ack_pkt2(my_tb, temp_list): while temp_list: pktno, time_data, seed, virtual_frame = temp_list.pop(0) ack_pktno = pktno payload_prefix = struct.pack('!H', ack_pktno & 0xffff) data_size = len(payload_prefix) + timestamp_len + len(seed) + len(virtual_frame) dummy_data = (pkt_amt - data_size) * chr(ack_pktno & 0xff) now_timestamp_str = '{:.3f}'.format(time.time()) payload = payload_prefix + now_timestamp_str + seed + virtual_frame + dummy_data my_tb.txpath.send_pkt(payload) #sys.stderr.write('.') time_data_str = str(datetime.fromtimestamp(time_data)) print "Ack pktno {}, time {}, ack_pktno {}, seed {}, vf {}".format(pktno, time_data_str, ack_pktno, seed, virtual_frame) time.sleep(0.001) #my_tb.txpath.send_pkt(eof=True) time.sleep(0.005) def rx_callback(ok, payload): global n_rcvd, n_right, stop_init_pkt n_rcvd += 1 (pktno,) = struct.unpack('!H', payload[0:2]) # Filter out incorrect pkt if pktno >= wrong_pktno: print "wrong pktno {}".format(pktno) return try: pkt_timestamp_str = payload[2:2+timestamp_len] pkt_timestamp = float(pkt_timestamp_str) except: print "{} is not a float.".format(pkt_timestamp_str) return seed = payload[2+timestamp_len:2+timestamp_len+seed_len] virtual_frame = payload[2+timestamp_len+seed_len:2+timestamp_len+seed_len+vf_len] now_timestamp = round(time.time(), 3) time_delta = now_timestamp - pkt_timestamp rx_time = str(datetime.fromtimestamp(pkt_timestamp)) if pktno == 0: # is beacon print "received beacon. time: {}\tdelay: {}".format(rx_time, time_delta) return if ok: n_right += 1 #print "received pkt. ok: %r \t pktno: %d \t time: %s \t delay: %f \t n_rcvd: %d \t n_right: %d" % (ok, pktno, rx_time, time_delta, n_rcvd, n_right) print "received pkt. ok: {}\tpktno: {}\ttime: {}\tdelay: {}\tseed: {}\tvf: {}".format(ok, pktno, rx_time, time_delta, seed, virtual_frame) data_list.append((pktno, pkt_timestamp, seed, virtual_frame)) if len(data_list) >= 10: stop_init_pkt = True def check_thread_is_done(iter_limit): for i in range(1000): if not my_thread.is_alive() and my_iterations >= iter_limit: # thread done, proceed to next break time.sleep(0.002) print "{} thread is done".format(str(datetime.now())) ####### # main ####### parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-s", "--size", type="eng_float", default=400, help="set packet size [default=%default]") parser.add_option("-M", "--megabytes", type="eng_float", default=1.0, help="set megabytes to transmit [default=%default]") parser.add_option("","--discontinuous", action="store_true", default=False, help="enable discontinuous mode") parser.add_option("","--from-file", default=None, help="use intput file for packet contents") parser.add_option("","--to-file", default=None, help="Output file for modulated samples") digital.ofdm_mod.add_options(parser, expert_grp) digital.ofdm_demod.add_options(parser, expert_grp) transmit_path.add_options(parser, expert_grp) receive_path.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) uhd_receiver.add_options(parser) (options, args) = parser.parse_args () if len(args) != 0: parser.print_help(sys.stderr) sys.exit(1) print "----------------------------------------------------------" print "Input options: \n{}".format(str(options)) print "----------------------------------------------------------\n" if options.rx_freq is None or options.tx_freq is None: sys.stderr.write("You must specify -f FREQ or --freq FREQ\n") parser.print_help(sys.stderr) sys.exit(1) # build the tx/rx graph tb = TopBlock(rx_callback, options) #init_tb() # tb_rx = rx_top_block(rx_callback, options) # tb_tx = tx_top_block(options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() pkt_amt = int(options.size) print "pkt_amt {}".format(pkt_amt) pkt_amount = 100 # Send beacon signals. Time precision: New thread do_every(0.005, send_beacon_pkt2, tb, pkt_amount) # New thread checks last thread is done check_thread_is_done(pkt_amount) # Send initial data packets. Time precision: New thread do_every(0.005, send_init_pkt2, tb, pkt_amount) # New thread checks last thread is done check_thread_is_done(pkt_amount) # send_init_pkt(tb, MAX_PKT_AMT) # Iteration for switching between beacon signals & data packets # iterate = 0 # while iterate < MAX_ITERATION: # print "iterate {}: data_list len {}".format(iterate, len(data_list)) # iterate += 1 # if data_list: # send_ack_pkt2(tb, data_list) # # New thread checks last thread is done # check_thread_is_done(50) # else: # do_every(0.005, send_beacon_pkt2, tb, 50) # # Another thread to check last thread is done # check_thread_is_done(50) # TODO: Estimate when send EOF will finish... But does it needed? # time.sleep(5) # print "TX send EOF pkt.............." # tb.txpath.send_pkt(eof=True) #tb.stop() tb.wait()
def main(): mods = digital.modulation_utils.type_1_mods() demods = digital.modulation_utils.type_1_demods() parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='gmsk', help="Select modulation from: %s [default=%%default]" % (', '.join(mods.keys()), )) parser.add_option("-s", "--size", type="eng_float", default=1500, help="set packet size [default=%default]") parser.add_option("-v", "--verbose", action="store_true", default=False) # WYQ parser.add_option("-p", "--PLR", type="intx", default=3, help="set packet loss rate [default=%default]") expert_grp.add_option( "-c", "--carrier-threshold", type="eng_float", default=30, help="set carrier detect threshold (dB) [default=%default]") expert_grp.add_option("", "--tun-device-filename", default="/dev/net/tun", help="path to tun device file [default=%default]") transmit_path.add_options(parser, expert_grp) receive_path.add_options(parser, expert_grp) uhd_receiver.add_options(parser) uhd_transmitter.add_options(parser) for mod in mods.values(): mod.add_options(expert_grp) for demod in demods.values(): demod.add_options(expert_grp) (options, args) = parser.parse_args() if len(args) != 0: parser.print_help(sys.stderr) sys.exit(1) # open the TUN/TAP interface #(tun_fd, tun_ifname) = open_tun_interface(options.tun_device_filename) if options.rx_freq is None or options.tx_freq is None: sys.stderr.write("You must specify -f FREQ or --freq FREQ\n") parser.print_help(sys.stderr) sys.exit(1) received_file = open('./output_no_raptor.264', 'w') # Attempt to enable realtime scheduling r = gr.enable_realtime_scheduling() if r == gr.RT_OK: realtime = True else: realtime = False print "Note: failed to enable realtime scheduling" # instantiate the MAC #mac = cs_mac(tun_fd, verbose=True) mac = cs_mac(options.PLR, received_file, verbose=True) # build the graph (PHY) tb = my_top_block(mods[options.modulation], demods[options.modulation], mac.phy_rx_callback, options) mac.set_top_block(tb) # give the MAC a handle for the PHY if tb.txpath.bitrate() != tb.rxpath.bitrate(): print "WARNING: Transmit bitrate = %sb/sec, Receive bitrate = %sb/sec" % ( eng_notation.num_to_str(tb.txpath.bitrate()), eng_notation.num_to_str(tb.rxpath.bitrate())) print "modulation: %s" % (options.modulation, ) print "freq: %s" % (eng_notation.num_to_str(options.tx_freq)) print "bitrate: %sb/sec" % (eng_notation.num_to_str( tb.txpath.bitrate()), ) print "samples/symbol: %3d" % (tb.txpath.samples_per_symbol(), ) tb.rxpath.set_carrier_threshold(options.carrier_threshold) print "Carrier sense threshold:", options.carrier_threshold, "dB" #print #print "Allocated virtual ethernet interface: %s" % (tun_ifname,) #print "You must now use ifconfig to set its IP address. E.g.," #print #print " $ sudo ifconfig %s 192.168.200.1" % (tun_ifname,) #print #print "Be sure to use a different address in the same subnet for each machine." #print tb.start() # Start executing the flow graph (runs in separate threads) #mac.main_loop() # don't expect this to return... #tb.stop() # but if it does, tell flow graph to stop. tb.wait() # wait for it to finish received_file.close()
def main(): def ncycle(iterable, n): for item in itertools.cycle(iterable): for i in range(n): yield item hop_interval = 1000.0 # ms maxium_resend = 100 pkt_size = 10 seq0 = ncycle([0, 0, 0, 1, 2], 1) seq1 = ncycle([1, 1, 0, 1, 2, 2, 0], 1) seq2 = ncycle([2, 2, 2, 1, 2, 0, 0, 1], 1) seqs = [seq0, seq1, seq2] def rx_callback(ok, payload): global rx_callback_enable, cnt, numrec, returnack if (ok and rx_callback_enable == 1): #if (len(payload) >= 1): if (payload[0] == 'B'): #FreCtrl.printSpace() #print "Receive Beacon"#, payload synch.Synch(int(payload[1:])) returnack = 1 myPay.getACK(synch.getRemainTime()) tb.send_pkt(myPay) else: if 97 <= ord(payload) <= 122: if ord(payload) == 122: tb.send_pkt(chr(97)) else: tb.send_pkt((payload + 1)) #FreCtrl.printSpace() #print "Receive Data", int(payload[1:11]) #myPay.updatePkt(payload[1:11], payload[12:]) #save the packet to the file #tb.send_pkt('0+', payload) #tb.send_pkt('1+', payload) #tb.send_pkt('2+', payload) #tb.send_pkt('3+', payload) #tb.send_pkt('4+', payload) parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("", "--discontinuous", action="store_true", default=False, help="enable discontinuous") parser.add_option("", "--from-file", default=None, help="input file of samples to demod") parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-s", "--size", type="eng_float", default=40, help="set packet size [default=%default]") parser.add_option("-M", "--megabytes", type="eng_float", default=1.0, help="set megabytes to transmit [default=%default]") parser.add_option("", "--discontinuous", action="store_true", default=False, help="enable discontinuous mode") parser.add_option("", "--from-file", default=None, help="use intput file for packet contents") parser.add_option("", "--to-file", default=None, help="Output file for modulated samples") receive_path.add_options(parser, expert_grp) uhd_receiver.add_options(parser) digital.ofdm_demod.add_options(parser, expert_grp) transmit_path.add_options(parser, expert_grp) digital.ofdm_mod.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) (options, args) = parser.parse_args() if len(args) != 0: parser.print_help(sys.stderr) sys.exit(1) # Attempt to enable realtime scheduling r = gr.enable_realtime_scheduling() if r == gr.RT_OK: realtime = True else: realtime = False print "Note: failed to enable realtime scheduling" # build the graph (PHY) tb = my_top_block(rx_callback, options) synch = Synchronize(hop_interval) myPay = payload_mgr('./rcvd_file/rcvd_file.bmp') debug = write_info('./rx_info.txt') FreCtrl = frequency_mgr(seqs) FreCtrl.check_main( ) #check whethetr the channel you post with the flag is in the seqs FreCtrl.set_frequency(tb) startRun = datetime.datetime.now() tb.start() # Start5 executing the flow graph (runs in separate threads) while True: #myPay.getSize() < 60000: global rx_callback_enable rx_callback_enable = 0 synch.startSlot = datetime.datetime.now() FreCtrl.printSpace() if (tb.rxpath.variable_function_probe_0 == 0): print "Primary user is absent... start..." rx_callback_enable = 1 time.sleep(synch.getInterval() / 1000) else: print "Primary user is present...wait..." FreCtrl.set_frequency(tb) #os.system('xdg-open ./rcvd_file/rcvd_file.bmp') tb.wait() # wait for it to finish
def main(): #import protocol model vfs_model = VirtualFrameScheme(PacketType, NODE_SLOT_TIME) #node rx queue/event global node_rx_q, node_rx_sem, thread_run, alloc_index, last_node_amount,file_input,\ file_output, data, data_num, upload_file node_rx_q = Queue.Queue(maxsize=NODE_RX_MAX) node_rx_sem = threading.Semaphore(NODE_RX_MAX) #up to the queue size thread_run = True alloc_index = -1 last_node_amount = -1 last_in_noaction = True data = "**heLLo**" # default data str data_num = 0 upload_file = True for i in range(NODE_RX_MAX): # make all semaphore in 0 status node_rx_sem.acquire() def send_pkt(payload='', eof=False): return tb.txpath.send_pkt(payload, eof) global n_rcvd, n_right n_rcvd = 0 n_right = 0 def rx_callback(ok, payload): global n_rcvd, n_right n_rcvd += 1 # Filter out incorrect pkt if ok: thingy = decode_common_pkt_header(tb, payload) if not thingy: return (pktno, pkt_timestamp, pkt_type) = thingy n_right += 1 now_ts = tb.sink.get_time_now().get_real_secs() node_rx_q.put(payload) else: logger.warning("Packet fail. Drop pkt!") return parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") # parser.add_option("","--discontinuous", action="store_true", default=False, # help="enable discontinuous") parser.add_option("", "--from-file", default=None, help="input file of samples") # parser.add_option("-M", "--megabytes", type="eng_float", default=1.0, # help="set megabytes to transmit [default=%default]") parser.add_option("-s", "--size", type="eng_float", default=400, help="set packet size [default=%default]") parser.add_option("-p", "--packno", type="eng_float", default=0, help="set packet number [default=%default]") parser.add_option("", "--to-file", default=None, help="Output file for modulated samples") parser.add_option("", "--bs", default=None, help="assign if bs") transmit_path.add_options(parser, expert_grp) digital.ofdm_mod.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) receive_path.add_options(parser, expert_grp) uhd_receiver.add_options(parser) digital.ofdm_demod.add_options(parser, expert_grp) (options, args) = parser.parse_args() # Decide is BS or Node role IS_BS_ROLE = bool(options.bs) if options.from_file is None: if options.rx_freq is None: sys.stderr.write("You must specify -f FREQ or --freq FREQ\n") parser.print_help(sys.stderr) sys.exit(1) if options.packno is not None: packno_delta = options.packno logger.info("assign pktno start: %d" % packno_delta) # build the graph tb = my_top_block(rx_callback, options) # USRP device aligns with PC time (NTP) pc_now = time.time() tb.sink.set_time_now(uhd.time_spec(pc_now)) tb.source.set_time_now(uhd.time_spec(pc_now)) now_ts = tb.sink.get_time_now().get_real_secs() logger.info("\n{} Adjust to PC time: {}\n".format( str(datetime.fromtimestamp(time.time())), str(datetime.fromtimestamp(now_ts)))) # get this node id NODE_ID = tb.sink.get_usrp_mboard_serial() # Append to required length NODE_ID = NODE_ID.zfill(NODE_ID_LEN) assert len( NODE_ID) == NODE_ID_LEN, "USRP NODE_ID {} len must be {}".format( NODE_ID, NODE_ID_LEN) logger.info("\nNODE ID: {}".format(NODE_ID)) #realtime scheduling r = gr.enable_realtime_scheduling() if r != gr.RT_OK: logger.warn("Warning: failed to enable realtime scheduling") # node, open input file if assigned if not IS_BS_ROLE and (options.from_file is not None): try: file_input = open(options.from_file, "r") data = file_input.read(3) upload_file = True logger.info("Input file opened successfully") except: logger.error("Error: file not exist") elif not IS_BS_ROLE: upload_file = False data = str(data_num) else: pass # bs, open output file if assigned if IS_BS_ROLE and (options.to_file is not None): try: file_output = open(options.to_file, "w+", buffering=0) #no buffering, flush rightaway logger.info("Output file opened successfully") except: logger.error("Error: file not exist") tb.start() # start flow graph n = 0 pktno = 0 pkt_size = int(options.size) def threadjob(pktno, IS_BS, NODE_ID): global thread_run, data, data_num, TEST_NODE_RETRY, TEST_NODE_LIST, i_care_ack, last_pktno logger.info("Please start host now...") boot_time = time.time() bs_start_time = 0 nd_start_time = 0 nd_in_response = False not_my_business = False time_data_collecting = len(TEST_NODE_LIST) * NODE_SLOT_TIME time_wait_for_my_slot = 0 TEST_NODE_RETRY[:] = list(TEST_NODE_RETRY_DEFAULT) TEST_NODE_LIST = list(TEST_NODE_LIST_DEFAULT) last_data = -1 i_care_ack = False last_pktno = -1 print(TEST_NODE_LIST) print(TEST_NODE_LIST_DEFAULT) while thread_run: if IS_BS: if time.time() > (bs_start_time + time_data_collecting + TRANSMIT_DELAY): #statstic if pktno != 0: for iid in TEST_NODE_RETRY: logger.info("111111111111111111111111111") logger.info("1 Data Timeout:{} 1".format(iid)) logger.info("111111111111111111111111111") statistics[iid]['Missing'] += 1 temp = 0 for iid in TEST_NODE_RETRY_DEFAULT: if iid in TEST_NODE_LIST: temp = vfs_model.query_vack(iid) if 1 == temp: statistics[iid]['ACK'] += 1 elif 2 == temp: statistics[iid]['NAK'] += 1 else: pass print(statistics) print("\n......Frame start......") #prepare if pktno != 0: i = 0 TEST_NODE_LIST[:] = [] #prepare - scheduling for iid in TEST_NODE_LIST_DEFAULT: # join this run, for all scheduled or retry devices if pktno % TEST_NODE_SCHEDULE[i] == 0: TEST_NODE_LIST.append(iid) logger.info("scheduled:{}".format(iid)) #statstic if iid in statistics: statistics[iid]['Schedule'] += 1 elif iid in TEST_NODE_RETRY: TEST_NODE_LIST.append(iid) logger.info("retry:{}".format(iid)) #statstic if iid in statistics: statistics[iid]['Retry'] += 1 else: pass #TEST_NODE_LIST.append("000000000{}".format(i+1)) i = i + 1 TEST_NODE_RETRY[:] = [] for iid in TEST_NODE_RETRY_DEFAULT: if iid in TEST_NODE_LIST: TEST_NODE_RETRY.append(iid) else: #statstic for iid in statistics: statistics[iid]['Schedule'] += 1 vfs_model.generate_seed_v_frame_rand_frame2( TEST_NODE_LIST_DEFAULT, TEST_NODE_LIST) #statstic if '00030757AF' in vfs_model.rand_frame and '00030757AF' in TEST_NODE_LIST: statistics['00030757AF']['Rand'] += 1 if '000307B24B' in vfs_model.rand_frame and '000307B24B' in TEST_NODE_LIST: statistics['000307B24B']['Rand'] += 1 #send boardcast vfs_model.send_dummy_pkt( tb) # hacking, send dummy pkt to avoid data lost vfs_model.broadcast_vfs_pkt(tb, pkt_size, len(TEST_NODE_LIST), pktno + int(packno_delta)) pktno += 1 #statistic statistics['00030757AF']['Bcast'] = pktno statistics['000307B24B']['Bcast'] = pktno bs_start_time = time.time() else: pass #vfs_model.send_dummy_pkt(tb) else: #node if nd_in_response and time.time() > (nd_start_time + time_wait_for_my_slot): if not_my_business: #this run is not my run pass else: logger.info("data on hand {}".format(data)) #prepare data if upload_file: try: file_input.seek(3 * data_num) data = file_input.read(3) if data == '': thread_run = False tb.txpath.send_pkt(eof=True) tb.stop() break logger.info( "read current data {}".format(data)) except: #error end thread_run = False tb.txpath.send_pkt(eof=True) else: data = str(data_num) if data == str(TEST_DATA_MAX + 1): thread_run = False tb.txpath.send_pkt(eof=True) tb.stop() break logger.info("read current data {}".format(data)) vfs_model.send_dummy_pkt( tb) # hacking, send dummy pkt to avoid data lost vfs_model.send_vfs_pkt(NODE_ID, tb, pkt_size, data, data_num, pktno) i_care_ack = True logger.info( "\n===========================\npktno:{}\ndata numer:{}\ndata:{}\nstatistics:{}\n===========================" .format(pktno, data_num, data, statistics_dev[NODE_ID])) pktno += 1 nd_in_response = False not_my_business = False else: #print "nd_in_response{}, time {} > {} ".format(nd_in_response,time.time(), (nd_start_time + time_wait_for_my_slot)) pass #vfs_model.send_dummy_pkt(tb) #tb.txpath.send_pkt(eof=True) #while node_rx_sem.acquire(False): if not node_rx_q.empty(): payload = node_rx_q.get() if payload: #here we need to decode the payload first if IS_BS: thingy = action(tb, vfs_model, payload, NODE_ID) if thingy: (delta, node_id, node_pktno, upload_data, data_number) = thingy #check the data number in payload if vfs_model.check_data_num(node_id, data_number): logger.info("data:{} length:{}".format( upload_data, len(upload_data))) vfs_model.set_data_num( node_id, data_number + 1 & 0xffff) #keep track in vfs module try: #file_output.write(upload_data) writefile(node_id, upload_data) except: logger.info("write file fail") if upload_data == str(TEST_DATA_MAX): logger.info("=====test end=====") thread_run = False tb.txpath.send_pkt(eof=True) tb.stop() break if int(upload_data) != (last_data + 1): logger.info( "=====Error protocol fail=====upload{},check{}" .format(upload_data, last_data + 1)) thread_run = False tb.txpath.send_pkt(eof=True) tb.stop() break last_data = last_data + 1 TEST_NODE_RETRY.remove(node_id) else: logger.info("2222222222222222") logger.info("2 SEQ mismatch 2") logger.info("2222222222222222") statistics[node_id]['SEQ'] += 1 TEST_NODE_RETRY.remove(node_id) else: logger.critical("[Decode Error] payload fail") logger.info("3333333333333333") logger.info("3 Payload Error3") logger.info("3333333333333333") statistics['00030757AF']['Decode'] += 1 statistics['000307B24B']['Decode'] += 1 else: logger.info("\n... get broadcast ...") statistics_dev[NODE_ID]['GotBcast'] += 1 thingy = action(tb, vfs_model, payload, NODE_ID) if thingy: if "not-my-business" == thingy: #not schedule in this run nd_in_response = True not_my_business = True else: #success and check (node_amount, seed, delta, vf_index, alloc_index, in_rand_frame, v_frame) = thingy time_wait_for_my_slot = alloc_index * NODE_SLOT_TIME nd_start_time = time.time() nd_in_response = True if in_rand_frame: logger.info("666666666666666666666666666") logger.info("6 Rand Frame - SKIP 6") logger.info("666666666666666666666666666") statistics_dev[NODE_ID]['RAND'] += 1 not_my_business = True elif alloc_index < 0: logger.info("555555555555555555555555555") logger.info("5 No Action 5") logger.info("555555555555555555555555555") not_my_business = True statistics_dev[NODE_ID]['NoAction'] += 1 else: logger.info( "I will upload at slot {}, wait for {}s" .format(alloc_index, time_wait_for_my_slot)) not_my_business = False statistics_dev[NODE_ID]['askup'] += 1 #vfs_model.send_vfs_pkt( NODE_ID, tb, pkt_size, "**heLLo**{}".pktno, pktno) else: logger.warn("error during decode VFS_BROADCAST") logger.info("777777777777777777777777777") logger.info("7 Decode 7") logger.info("777777777777777777777777777") statistics_dev[NODE_ID]['Decode'] += 1 print "... thread out ..." #node_rx_sem.release thread = threading.Thread(target=threadjob, args=(pktno, IS_BS_ROLE, NODE_ID)) thread.daemon = True #make it a daemon thread thread_run = True thread.start() time.sleep(2) # allow time for queued packets to be sent tb.wait() # wait for it to finish thread_run = False while thread.isAlive(): time.sleep(1) try: file_input.close() except: pass try: file_output.close() except: pass print "join done"
def main(): def send_pkt(payload='', eof=False): return tb.txpath.send_pkt(payload, eof) mods = digital.modulation_utils.type_1_mods() parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='gfsk', help="Select modulation from: %s [default=%%default]" % (', '.join(mods.keys()), )) parser.add_option("-s", "--size", type="eng_float", default=1500, help="set packet size [default=%default]") parser.add_option("-M", "--megabytes", type="eng_float", default=1.0, help="set megabytes to transmit [default=%default]") parser.add_option( "", "--discontinuous", action="store_true", default=False, help="enable discontinous transmission (bursts of 5 packets)") parser.add_option("", "--from-file", default=None, help="use intput file for packet contents") parser.add_option("", "--to-file", default=None, help="Output file for modulated samples") parser.add_option("-E", "--exp-id", type="string", default="test", help="specify the experiment ID") parser.add_option("-N", "--node-id", type="string", default="tx", help="specify the experiment ID") parser.add_option("", "--server", action="store_true", default=False, help="To take data from the server") parser.add_option("", "--port", type="int", default=None, help="specify the server port") transmit_path.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) for mod in mods.values(): mod.add_options(expert_grp) (options, args) = parser.parse_args() omlDb = OMLBase("gnuradiorx", options.exp_id, options.node_id, "tcp:nitlab3.inf.uth.gr:3003") omlDb.addmp("packets", "type:string value:long") omlDb.start() if len(args) != 0: parser.print_help() sys.exit(1) if options.from_file is not None: source_file = open(options.from_file, 'r') # build the graph tb = my_top_block(mods[options.modulation], options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() # start flow graph start = time.time() # generate and send packets nbytes = int(1e6 * options.megabytes) n = 0 pktno = 0 pkt_size = int(options.size) buffer = [] stable_buffer = [] once = 1 # connect to server if options.server: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #server_address = ('10.0.1.200', 50000) server_address = ('10.0.1.200', options.port) print >> sys.stderr, 'connecting to %s port %s' % server_address sock.connect(server_address) while pktno < 1000: if n < nbytes or options.server: if options.server: data = "" while len(data) < pkt_size: data += sock.recv(pkt_size - len(data)) if data == '': # No more data received from server sock.close() break elif options.from_file is None: data = (pkt_size - 2) * chr(pktno & 0xff) else: data = source_file.read(pkt_size - 2) if data == '': break payload = struct.pack('!H', pktno & 0xffff) + data buffer.insert(pktno, payload) stable_buffer.insert(pktno, payload) send_pkt(payload) n += len(payload) sys.stderr.write('.') omlDb.inject("packets", ("sent", pktno)) if options.discontinuous and pktno % 5 == 4: time.sleep(1) pktno += 1 else: break while buffer: current_elapsed = time.time() - start if current_elapsed >= 3 and once == 1: options.bitrate = 1.3e6 once = 0 #gr.top_block.__init__(tb) args = mods[options.modulation].extract_kwargs_from_options( options) modulator = mods[options.modulation] symbol_rate = options.bitrate / modulator(**args).bits_per_symbol() tb.sink.set_sample_rate(symbol_rate, options.samples_per_symbol) options.tx_freq += 0.75e6 tb.sink.set_freq(options.tx_freq, options.lo_offset) #print "from options.......... ", options.tx_freq print "IN FREQ", tb.sink._freq #print "WITH BITRATE ", options.bitrate #print "BITRATE FROM TB ", tb.txpath._bitrate for i in range(0, pktno): print "BITRATE FROM get ", tb.txpath.bitrate() send_pkt(buffer[i]) send_pkt(eof=True) tb.wait() # wait for it to finish
def main(): users = [str(i) for i in range(NUM_USRP)] parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option( "--target", type="string", default='', help="Which user to communicate:0,1,2... [default=%%default]") parser.add_option( "-m", "--modulation", type="choice", choices=['bpsk', 'qpsk'], default='bpsk', help="Select modulation from: bpsk, qpsk [default=%%default]") parser.add_option("-v", "--verbose", action="store_true", default=False) expert_grp.add_option( "-c", "--carrier-threshold", type="eng_float", default=30, help="set carrier detect threshold (dB) [default=%default]") expert_grp.add_option("", "--tun-device-filename", default="/dev/net/tun", help="path to tun device file [default=%default]") digital.ofdm_mod.add_options(parser, expert_grp) digital.ofdm_demod.add_options(parser, expert_grp) transmit_path.add_options(parser, expert_grp) receive_path.add_options(parser, expert_grp) uhd_receiver.add_options(parser) uhd_transmitter.add_options(parser) (options, args) = parser.parse_args() if len(args) != 0: parser.print_help(sys.stderr) sys.exit(1) if options.target not in users: print "Error: You must specify correct target user!" parser.print_help(sys.stderr) sys.exit(1) ''' if options.rx_freq is None or options.tx_freq is None: sys.stderr.write("You must specify -f FREQ or --freq FREQ\n") parser.print_help(sys.stderr) sys.exit(1) ''' global TARGET_USER TARGET_USER = int(options.target) # open the TUN/TAP interface (tun_fd, tun_ifname) = open_tun_interface(options.tun_device_filename) tun_config(tun_ifname) # Attempt to enable realtime scheduling r = gr.enable_realtime_scheduling() if r == gr.RT_OK: realtime = True else: realtime = False print "Note: failed to enable realtime scheduling" # instantiate the MAC mac = cs_mac(tun_fd, verbose=True) # build the graph (PHY) options.bandwidth = BAND_USRPS[TARGET_USER] options.tx_freq = TXFREQ_USRPS[TARGET_USER] options.rx_freq = RXFREQ_USRPS[TARGET_USER] options.args = ADDR_USRPS[TARGET_USER] tb = my_top_block(mac.phy_rx_callback, options) mac.set_flow_graph(tb) # give the MAC a handle for the PHY print "modulation: %s" % (options.modulation, ) print "freq: %s" % (eng_notation.num_to_str(options.tx_freq)) tb.rxpath.set_carrier_threshold(options.carrier_threshold) print "Carrier sense threshold:", options.carrier_threshold, "dB" print print "Allocated virtual ethernet interface: %s" % (tun_ifname, ) print "You must now use ifconfig to set its IP address. E.g.," print print " $ sudo ifconfig %s 192.168.200.1" % (tun_ifname, ) print print "Be sure to use a different address in the same subnet for each machine." print tb.start() # Start executing the flow graph (runs in separate threads) threading.Thread(target=mac.arq_fsm).start() # mac.main_loop() # don't expect this to return... # tb.stop() # but if it does, tell flow graph to stop. tb.wait() # wait for it to finish
def main(): gnlogger.logconf() # initializes the logging facility module_logger.info('start this module') mods = digital.modulation_utils.type_1_mods() demods = digital.modulation_utils.type_1_demods() parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='bpsk', help="Select modulation from: %s [default=%%default]" % (', '.join(mods.keys()),)) parser.add_option("-s", "--size", type="eng_float", default=100, help="set packet size [default=%default]") parser.add_option("-M", "--megabytes", type="eng_float", default=1.0, help="set megabytes to transmit [default=%default]") parser.add_option("","--discontinuous", action="store_true", default=False, help="enable discontinous transmission (bursts of 5 packets)") parser.add_option("","--from-file", default=None, help="use intput file for packet contents") parser.add_option("","--to-file", default=None, help="Output file for modulated samples") parser.add_option("", "--mac", default=None , help = "MAC addres") parser.add_option("", "--version", default='6' , help = "gnuradio version, default 6 (3.6)") parser.add_option("", "--mac_dst", default=None , help = "Destination MAC addres") parser.add_option("","--master", action="store_true",default=False, dest= 'master', help="Master in TDMA Network") parser.add_option("","--slave", action="store_false",default=False, dest= 'master', help="Slave in TDMA Network") tp36.add_options(parser, expert_grp) tp37.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) rp36.add_options(parser, expert_grp) rp37.add_options(parser, expert_grp) uhd_receiver.add_options(parser) for mod in demods.values(): mod.add_options(expert_grp) for mod in mods.values(): mod.add_options(expert_grp) (options, args) = parser.parse_args () if len(args) != 0: parser.print_help() sys.exit(1) if options.from_file is not None: source_file = open(options.from_file, 'r') r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" q_L1_tx =Queue.Queue(10) q_L1_rx =Queue.Queue(10) l1=StartL1(q_L1_rx,q_L1_tx,options,mods[options.modulation],demods[options.modulation]) l1.start() schL1_L2= StartSchedL1_L2(q_L1_rx,q_L1_tx) schL1_L2.start() # POR AHORA NO USO CAPA MAC # l2Mgmt=StartL2Mgmt(schL1_L2.mgmt_q1,schL1_L2.tx_ev_q,options.mac,"256","Red IIE") # l2Mgmt.start() L2_ctrl_rx_q =Queue.Queue(10) L2_data_rx_q =Queue.Queue(5) L2_event_tx_q = Queue.Queue(10) l3= schedLayer3.Layer3(L2_data_rx_q,L2_event_tx_q,'/dev/net/tun',options.mac,options.mac_dst) "OJO POR AHORA LE ESTOY PASANDO A LA MAC TDMA LA COLA DE MGMT Y NO LA CTRL PORQUE EL CANAL DE CONTRL ES UN BEACON____!!!!!!!" if options.master: net_conf = NetworkConfiguration.NetworkConfiguration(options.mac,'my network',256,1) net_conf.slots = 3 " The first slot is the control slot, the others are for data" net_conf.control_time = 0.9 " Each slot has 1 second" net_conf.list_nodes.append(options.mac) net_conf.list_nodes.append(options.mac_dst) mac_tdma = Mac.MacTdma(net_conf,schL1_L2.mgmt_q,schL1_L2.data_q,L2_ctrl_rx_q,L2_data_rx_q,schL1_L2.tx_ev_q,L2_event_tx_q,options.master) else: net_conf = NetworkConfiguration.NetworkConfiguration(options.mac,'my network',256,1) mac_tdma = Mac.MacTdma(net_conf,schL1_L2.mgmt_q,schL1_L2.data_q,L2_ctrl_rx_q,L2_data_rx_q,schL1_L2.tx_ev_q,L2_event_tx_q,options.master) c = raw_input('Press #z to end, or #w to test commands :') while c != "#z": c = raw_input('Press #z to end, or #w to test commands :') print "Program ends" l3.stop() schL1_L2.stop() l1.stop() mac_tdma.stop() #POR AHORA NO ESTOY USANDO CAPA 2 # l2.stop() exit(0)
def main(): def send_pkt(payload='', eof=False): return tb.txpath.send_pkt(payload, eof) mods = digital.modulation_utils.type_1_mods() parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='psk', help="Select modulation from: %s [default=%%default]" % (', '.join(mods.keys()), )) parser.add_option("-s", "--size", type="eng_float", default=1500, help="set packet size [default=%default]") parser.add_option("-M", "--megabytes", type="eng_float", default=1.0, help="set megabytes to transmit [default=%default]") parser.add_option( "", "--discontinuous", action="store_true", default=False, help="enable discontinous transmission (bursts of 5 packets)") parser.add_option("", "--from-file", default=None, help="use intput file for packet contents") parser.add_option("", "--to-file", default=None, help="Output file for modulated samples") transmit_path.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) for mod in mods.values(): mod.add_options(expert_grp) (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() sys.exit(1) if options.from_file is not None: source_file = open(options.from_file, 'r') # build the graph tb = my_top_block(mods[options.modulation], options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() # start flow graph # generate and send packets nbytes = int(1e6 * options.megabytes) n = 0 pktno = 0 pkt_size = int(options.size) while n < nbytes: if options.from_file is None: data = (pkt_size - 2) * chr(pktno & 0xff) else: data = source_file.read(pkt_size - 2) if data == '': break payload = struct.pack('!H', pktno & 0xffff) + data send_pkt(payload) n += len(payload) sys.stderr.write('.') if options.discontinuous and pktno % 5 == 4: time.sleep(1) pktno += 1 # added by memcmanu 3/3/2020 print(pktno) send_pkt(eof=True) tb.wait() # wait for it to finish
def main(): def send_pkt(payload='', eof=False): return tb.txpath.send_pkt(payload, eof) def rx_callback(ok, payload): print "ok = %r, payload = '%s'" % (ok, payload) mods = digital.modulation_utils.type_1_mods() parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='gmsk', help="Select modulation from: %s [default=%%default]" % (', '.join(mods.keys()), )) parser.add_option("-M", "--megabytes", type="eng_float", default=0, help="set megabytes to transmit [default=inf]") parser.add_option("-I", "--audio-input", type="string", default="", help="pcm input device name. E.g., hw:0,0 or /dev/dsp") parser.add_option("", "--to-file", default=None, help="Output file for modulated samples") transmit_path.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) for mod in mods.values(): mod.add_options(expert_grp) parser.set_defaults(bitrate=50e3) # override default bitrate default (options, args) = parser.parse_args() if len(args) != 0: parser.print_help() sys.exit(1) if options.to_file is None: if options.tx_freq is None: sys.stderr.write("You must specify -f FREQ or --freq FREQ\n") parser.print_help(sys.stderr) sys.exit(1) # build the graph tb = my_top_block(mods[options.modulation], options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() # start flow graph # generate and send packets nbytes = int(1e6 * options.megabytes) n = 0 pktno = 0 while nbytes == 0 or n < nbytes: packet = tb.audio_rx.get_encoded_voice_packet() s = packet.to_string() send_pkt(s) n += len(s) sys.stderr.write('.') pktno += 1 send_pkt(eof=True) tb.wait() # wait for it to finish
def main(): parser = OptionParser(option_class=eng_option, conflict_handler="resolve") hydra_options = parser.add_option_group("HyDRA Options") hydra_options.add_option( "-2", "--one-virtual-radio", action="store_true", default=False, help="Run with ONE virtual radio instead [default=%default]") hydra_options.add_option( "", "--file-sink", action="store_true", default=False, help="Do not use USRP as sink. Use file instead [default=%default]") hydra_options.add_option("", "--fft-length", type="intx", default=5120, help="HyDRA FFT M size [default=%default]") parser.add_option("", "--tx-freq", type="eng_float", default=hydra_center_frequency, help="Hydra transmit frequency [default=%default]", metavar="FREQ") parser.add_option("-W", "--bandwidth", type="eng_float", default=4e6, help="Hydra sample_rate [default=%default]") vr1_options = parser.add_option_group("VR 1 Options") vr1_options.add_option("", "--vr1-bandwidth", type="eng_float", default=1e6, help="set bandwidth for VR 1 [default=%default]") vr1_options.add_option( "", "--vr1-freq", type="eng_float", default=hydra_center_frequency + vr1_initial_shift, help="set central frequency for VR 1 [default=%default]") vr2_options = parser.add_option_group("VR 2 Options") vr2_options.add_option("", "--vr2-bandwidth", type="eng_float", default=200e3, help="set bandwidth for VR 2 [default=%default]") vr2_options.add_option( "", "--vr2-freq", type="eng_float", default=hydra_center_frequency + vr2_initial_shift, help="set central frequency for VR 2 [default=%default]") uhd_transmitter.add_options(parser) (options, args) = parser.parse_args() # build the graph options_vr1 = dict2obj({ 'freq': options.vr1_freq, 'bandwidth': options.vr1_bandwidth }) options_vr2 = dict2obj({ 'freq': options.vr2_freq, 'bandwidth': options.vr2_bandwidth }) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print("Warning: failed to enable realtime scheduling") tb = my_top_block(options, options_vr1, options_vr2) tb.start() # start flow graph tb.wait() # wait for it to finish
def main(): mods = digital.modulation_utils.type_1_mods() demods = digital.modulation_utils.type_1_demods() parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='gmsk', help="Select modulation from: %s [default=%%default]" % (', '.join(mods.keys()), )) parser.add_option("-s", "--size", type="eng_float", default=1500, help="set packet size [default=%default]") parser.add_option("-v", "--verbose", action="store_true", default=False) expert_grp.add_option( "-c", "--carrier-threshold", type="eng_float", default=30, help="set carrier detect threshold (dB) [default=%default]") #expert_grp.add_option("","--tun-device-filename", default="/dev/net/tun", # help="path to tun device file [default=%default]") transmit_path.add_options(parser, expert_grp) receive_path.add_options(parser, expert_grp) uhd_receiver.add_options(parser) uhd_transmitter.add_options(parser) for mod in mods.values(): mod.add_options(expert_grp) for demod in demods.values(): demod.add_options(expert_grp) (options, args) = parser.parse_args() if len(args) != 0: parser.print_help(sys.stderr) sys.exit(1) # Attempt to enable realtime scheduling r = gr.enable_realtime_scheduling() if r == gr.RT_OK: realtime = True else: realtime = False print "Note: failed to enable realtime scheduling" # instantiate (create object) the MAC mac = cs_mac(verbose=True) # build the flow-graph (PHY) tb = my_top_block(mods[options.modulation], demods[options.modulation], mac.phy_rx_callback, options) mac.set_top_block(tb) # give the MAC a handle to control the PHY if tb.txpath.bitrate() != tb.rxpath.bitrate(): print "WARNING: Transmit bitrate = %sb/sec, Receive bitrate = %sb/sec" % ( eng_notation.num_to_str(tb.txpath.bitrate()), eng_notation.num_to_str(tb.rxpath.bitrate())) print "modulation: %s" % (options.modulation, ) print "freq: %s" % (eng_notation.num_to_str(options.tx_freq)) print "bitrate: %sb/sec" % (eng_notation.num_to_str( tb.txpath.bitrate()), ) print "samples/symbol: %3d" % (tb.txpath.samples_per_symbol(), ) tb.rxpath.set_carrier_threshold(options.carrier_threshold) print "Carrier sense threshold:", options.carrier_threshold, "dB" tb.start() # Start executing the flow graph (runs in separate threads) mac.main_loop(options.tx_freq) # don't expect this to return... tb.stop() # but if it does, tell flow graph to stop. tb.wait() # wait for it to finish
def main(): def send_pkt(payload='', eof=False): return tb.txpath.send_pkt(payload, eof) f = open("receive_file", 'w') global n_rcvd, n_right, check_beacon_count n_rcvd = 0 n_right = 0 def rx_callback(ok, payload): global n_rcvd, n_right, pktno, pktno_receive, check_beacon_count n_rcvd += 1 #(pktno,) = struct.unpack('!H', payload[0:2]) if ok: n_right += 1 #print "ok: %r \t pktno: %d \t n_rcvd: %d \t n_right: %d" % (ok, pktno, n_rcvd, n_right) if tb.freq / 1e6 != 600: if payload[0] == 'B': check_beacon_count = 0 time.sleep(0.01) for i in range( 0, 100 ): #if channel is f*****g dirty, send more time, it is a know-how send_pkt('A') waitime = float(payload[1:]) #print " receiving beacon: "+payload[0:] #print "receiving beacon " elif payload[0] == 'D': print " pkt #: " + payload[ 1:4] + " packet content: " + payload[ 4:] + " frequency(MHz): " + str(tb.freq / 1e6) check_beacon_count = 0 ''' time.sleep(0.01) for n in range(1,4): pktno_receive = pktno_receive + payload[n] if pktno == int(pktno_receive): pktno = pktno + 1 f.write(payload[4:]) for i in range(0,10): send_pkt('a' + str(pktno_receive)) print "receiving data" + str(pktno_receive) pktno_receive = '' elif payload[0] == 'F': time.sleep(0.01) f.close() for i in range(0,10): send_pkt('F') print payload[0:] ''' #printlst = list() #for x in payload[2:]: # t = hex(ord(x)).replace('0x', '') # if(len(t) == 1): # t = '0' + t # printlst.append(t) #printable = ''.join(printlst) #print "\n" parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("", "--discontinuous", action="store_true", default=True, help="enable discontinuous") parser.add_option("-M", "--megabytes", type="eng_float", default=1.0, help="set megabytes to transmit [default=%default]") parser.add_option("", "--from-file", default=None, help="input file of samples to demod") parser.add_option("-s", "--size", type="eng_float", default=400, help="set packet size [default=%default]") receive_path.add_options(parser, expert_grp) uhd_receiver.add_options(parser) digital.ofdm_demod.add_options(parser, expert_grp) transmit_path.add_options(parser, expert_grp) digital.ofdm_mod.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) (options, args) = parser.parse_args() tb = my_top_block(rx_callback, options) fre_mgr = frequency_mgr(tb, options) if options.from_file is None: if options.rx_freq is None: sys.stderr.write("You must specify -f FREQ or --freq FREQ\n") parser.print_help(sys.stderr) sys.exit(1) # build the graph(PHY) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() # start flow graph nbytes = int(1e6 * options.megabytes) n = 0 pktno = 0 pkt_size = int(options.size) data1 = -1 situation = 0 while 1: #check_beacon_count = check_beacon_count+1 #print str(tb.freq)+" MHz" #if (check_beacon_count > 1): # tb.change_freq(); # tb.set_tx_freq(tb.freq) # tb.set_rx_freq(tb.freq) # check_beacon_count =0 # print "\n" # print " Dose not receive any beacons" # print "\n" fre_mgr.query_database() #myPay. #n += len(payload) #sys.stderr.write('.') #if options.discontinuous and pktno % 5 == 4: # time.sleep(1) time.sleep(waitime / 1000) #time.sleep(0.1) #check.beacon = '' #print "the end of the interval" #pktno += 1 send_pkt(eof=True) tb.wait() # wait for it to finish
def main(): # Send packet function def send_pkt(payload='', eof=False): return tb.txpath.send_pkt(payload, eof) # Modulation initialization mods = digital.modulation_utils.type_1_mods() # Get user inputs parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='psk', help="Select modulation from: %s [default=%%default]" % (', '.join(mods.keys()), )) parser.add_option("-s", "--size", type="eng_float", default=1500, help="set packet size [default=%default]") parser.add_option("-M", "--megabytes", type="eng_float", default=1.0, help="set megabytes to transmit [default=%default]") parser.add_option( "", "--discontinuous", action="store_true", default=False, help="enable discontinous transmission (bursts of 5 packets)") parser.add_option("", "--from-file", default=None, help="use intput file for packet contents") parser.add_option("", "--to-file", default=None, help="Output file for modulated samples") # Send options selected by user to transmit_path file transmit_path.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) # Pass options selected to all modulator file (dbpsk, d8psk, dqpsk, gmsk...) for mod in mods.values(): mod.add_options(expert_grp) # Parse command-line for errors (options, args) = parser.parse_args() # Print errors and exit if len(args) != 0: parser.print_help() sys.exit(1) # Open the file which user wants to transmit if options.from_file is not None: source_file = open(options.from_file, 'r') # build the graph # Constructing transmission flowgraph and pass pointer to variable called "tb" tb = my_top_block(mods[options.modulation], options) #--> got to def my_top_block # Enable realtime scheduling r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" # Start construction of flowgraph tb.start() # start flow graph # generate and send packets nbytes = int(1e6 * options.megabytes) # Total byte to send, From command-line n = 0 # pktno = 0 # First packet number pkt_size = int(options.size) #Size of packet # send packets/file while n < nbytes: print "Sending: " + str(n) + "| bytes: " + str( nbytes) + " | Packet Size: " + str(pkt_size) if options.from_file is None: # Generate packet (if raw data transmission chosen) data = (pkt_size - 2) * chr(pktno & 0xff) else: # Generate packet (if data from file is chosen) data = source_file.read(pkt_size - 2) if data == '': break payload = struct.pack( '!H', pktno & 0xffff) + data # Construct packet, the easy way send_pkt( payload ) # Send packet through send_pkt function --> see def send_pkt() n += len(payload) sys.stderr.write('.') # If discontinues is selected then after a 4 byte send pause 1 second (Conjestion problem hack) if options.discontinuous and pktno % 5 == 4: time.sleep(1) pktno += 1 # Tell send function that we are done sending send_pkt(eof=True) # Keep running flowgraph until user kills it tb.wait() # wait for it to finish
def main(): def send_pkt(payload='', eof=False): return tb.txpath.send_pkt(payload, eof) parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-s", "--size", type="eng_float", default=1000, help="set packet size [default=%default]") parser.add_option("-M", "--megabytes", type="eng_float", default=1.0, help="set megabytes to transmit [default=%default]") parser.add_option("", "--discontinuous", action="store_true", default=False, help="enable discontinuous mode") parser.add_option("", "--from-file", default=None, help="use intput file for packet contents") parser.add_option("", "--to-file", default=None, help="Output file for modulated samples") transmit_path.add_options(parser, expert_grp) digital.ofdm_mod.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) (options, args) = parser.parse_args() # build the graph tb = my_top_block(options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() # start flow graph # generate and send packets nbytes = int(1e6 * options.megabytes) n = 0 pktno = 0 pkt_size = int(options.size) t1 = 0 t2 = 0 t_start = time.time() while n < nbytes: if options.from_file is None: data = (pkt_size - 2) * chr(pktno & 0xff) else: data = source_file.read(pkt_size - 2) if data == '': break payload = struct.pack('!H', pktno & 0xffff) + data send_pkt(payload) n += len(payload) # sys.stderr.write('.') if options.discontinuous and pktno % 5 == 4: time.sleep(1) pktno += 1 if pktno == 84: t1 = time.time() if pktno == 100: print "bandwidth_change" tb.set_bandwidth(9000000) t2 = time.time() send_pkt(eof=True) time.sleep(2) # allow time for queued packets to be sent tb.wait() # wait for it to finish print "%.6f" % (t2 - t1)
def main(): def rx_callback(ok, payload): global pktno, pktno_receive if ok: #if payload[0] == 'B': # print '\t'+"receiving beacon" + payload[0:] if payload[0] == 'A': #ack from beacon myPay.pause() myPay.type = 1 myPay.restart() #print '\t'+"receiving ack from beacon" ''' elif payload[0] == 'a': #ack from data myPay.pause() for n in range(1,4): pktno_receive = pktno_receive + payload[n] if pktno == int(pktno_receive): myPay.retry = 0 else: myPay.retry = 1 myPay.restart() print '\t'+"receiving ack from data" + payload[1:4] elif payload[0] == 'F': print "missino completed" ''' #print "\n" parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("","--discontinuous", action="store_true", default=True, help="enable discontinuous") parser.add_option("-M", "--megabytes", type="eng_float", default=1.0, help="set megabytes to transmit [default=%default]") parser.add_option("","--from-file", default=None, help="input file of samples to demod") parser.add_option("-s", "--size", type="eng_float", default=400, help="set packet size [default=%default]") receive_path.add_options(parser, expert_grp) uhd_receiver.add_options(parser) digital.ofdm_demod.add_options(parser, expert_grp) transmit_path.add_options(parser, expert_grp) digital.ofdm_mod.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) (options, args) = parser.parse_args () if options.from_file is None: if options.rx_freq is None: sys.stderr.write("You must specify -f FREQ or --freq FREQ\n") parser.print_help(sys.stderr) sys.exit(1) # build the graph(PHY) tb = my_top_block(rx_callback, options) lock = threading.Lock() myPay = payload_mgr(tb, lock, "thread", datetime.datetime.now(), "source_file") myPay.start() r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() # start flow graph while True: #???bout.waitime = -1 #global rx_callback_enable, trans_status, get_ack, randombackoff, ttRB, difscount, DIFS #trans_status = 0 #at the new frame, start with a beacon #rx_callback_enable = 0 time.sleep(0.499) myPay.pause() time.sleep(0.001) detection = myPay.feature_detect myPay.reset() if (detection != 0): myPay.tb.change_freq(); myPay.tb.set_tx_freq(myPay.tb.freq) myPay.tb.set_rx_freq(myPay.tb.freq) print " frequency changes" myPay.pause() myPay.reset() myPay.startSlot = datetime.datetime.now() myPay.restart() #??? time.sleep(0.010) #wait 10ms to detect #??? FreCtrl.printSpace() feel that is not necessary #print "ack status=", get_ack #if (tb.rxpath.variable_function_probe_0 == 0): #frequency assigned by controller # print "TV is absent... start..." #???bout.set_waitime() # rx_callback_enable = 1 #the right timing to receive #time.sleep(hop_interval/1000) #else: # print "TV is present...wait..." # FreCtrl.set_frequency(tb) #???rx_callback_enable = not bool(tb.rxpath.variable_function_probe_0) ''' nbytes = int(1e6 * options.megabytes) n = 0 pktno = 0 pkt_size = int(options.size) data1 = 97 print pkt_size while n < nbytes: if options.from_file is None: data = (pkt_size - 2) * chr(pktno & 0xff) else: data = source_file.read(pkt_size - 2) if data == '': break; payload = struct.pack('!H', pktno & 0xffff) + chr(data1) print "sending" + chr(data1) send_pkt(payload) data1 = data1 + 1 if data1 == 123: data1 = 97 #n += len(payload) sys.stderr.write('.') #time.sleep(1) #if options.discontinuous and pktno % 5 == 4: # time.sleep(1) pktno += 1 ''' send_pkt(eof=True)
def main(): global n_rcvd, n_right, rcv_buffer n_rcvd = 0 n_right = 0 rcv_buffer = list() def rx_callback(ok, payload): global n_rcvd, n_right, rcv_buffer n_rcvd += 1 (pktno, ) = struct.unpack('!H', payload[0:2]) if ok: n_right += 1 rcv_buffer.append((pktno, payload)) # print 'pktno=', pktno, ' payload=', payload[2:] print "ok: %r \t pktno: %d \t n_rcvd: %d \t n_right: %d" % ( ok, pktno, n_rcvd, n_right) # print ' received ', def send_pkt(payload='', eof=False): return tb.txpath.send_pkt(payload, eof) parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("", "--discontinuous", action="store_true", default=False, help="enable discontinuous") parser.add_option("", "--from-file", default=None, help="input file of samples to demod") parser.add_option("", "--to-file", default=None, help="Output file for modulated samples") parser.add_option("-s", "--size", type="eng_float", default=400, help="set packet size [default=%default]") parser.add_option("-M", "--megabytes", type="eng_float", default=1.0, help="set megabytes to transmit [default=%default]") #rcv receive_path.add_options(parser, expert_grp) uhd_receiver.add_options(parser) digital.ofdm_demod.add_options(parser, expert_grp) #trans transmit_path.add_options(parser, expert_grp) digital.ofdm_mod.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) (options, args) = parser.parse_args() if options.from_file is None: if options.rx_freq is None: sys.stderr.write("You must specify -f FREQ or --freq FREQ\n") parser.print_help(sys.stderr) sys.exit(1) # build the graph tb = my_top_block(rx_callback, options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() # start flow graph #trans nbytes = int(1e3 * options.megabytes) n = 0 pktno = 0 pkt_size = int(options.size) if 1: while n < nbytes: if options.from_file is None: #data = (pkt_size - 2) * (pktno & 0xff) data = 'hellognuradio' else: data = source_file.read(pkt_size - 2) if data == '': break payload = struct.pack('!H', pktno & 0xffff) + data send_pkt(payload) n += len(payload) print 'transmitting pktno = ', pktno pktno += 1 send_pkt(eof=True) last_rcv_time = time.clock() while 1: while len(rcv_buffer) > 0: (pktno, payload) = rcv_buffer.pop(0) print 'pktno = ', pktno, 'payload = ', payload[2:] now = time.clock() #if not sleep, it seems it will chew up all CPU! time.sleep(0.3) if (now - last_rcv_time > 2): break print '########################TEST tx_rx_self FINISHED################################' print '########################NOW BEGIN TESTING carrier sense##########################' tb.rxpath.set_carrier_threshold(2) print 'threshold = ', tb.rxpath.carrier_threshold() while 1: print 'carrier sense : ', tb.rxpath.carrier_sensed() time.sleep(0.1) tb.wait() # wait for it to finish
def main(): #Searches for static 1Mhz windows def find_hole(power_list): bin_start=0 bin_stop=0 bins=0 results = [] for i in range(0,len(power_list)): if power_list[i]< 40.0 : bins=bins+1 if bins == 34: bin_stop=i break else: bins=0 bin_start=i+1 if bin_stop == 0: return 0 results.append(bin_start) results.append(bin_stop) return results #Attemp to find where opponent transmits def fuzz_target(power_list): bin_start=0 bin_stop=0 for i in range(0,len(power_list)): if power_list[i] > 60.0 : bin_start = i if (i+34) <= len(power_list): bin_stop = i+34 else: bin_stop = len(power_list) break if bin_start == 0: return 0 middle_bin = ((bin_stop-bin_start)/2) + bin_start result = (middle_bin*27902) + 2357500000.0 return result def send_pkt(payload='', eof=False): return tb.txpath.send_pkt(payload, eof) mods = digital.modulation_utils.type_1_mods() parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='qpsk', help="Select modulation from: %s [default=%%default]" % (', '.join(mods.keys()),)) parser.add_option("-s", "--size", type="eng_float", default=1500, help="set packet size [default=%default]") parser.add_option("-M", "--megabytes", type="eng_float", default=1.0, help="set megabytes to transmit [default=%default]") parser.add_option("","--discontinuous", action="store_true", default=False, help="enable discontinous transmission (bursts of 5 packets)") parser.add_option("","--from-file", default=None, help="use intput file for packet contents") parser.add_option("","--to-file", default=None, help="Output file for modulated samples") parser.add_option("","--server", action="store_true", default=False, help="To take data from the server") transmit_path.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) for mod in mods.values(): mod.add_options(expert_grp) (options, args) = parser.parse_args () if len(args) != 0: parser.print_help() sys.exit(1) if options.from_file is not None: source_file = open(options.from_file, 'r') # build the graph # tb = my_top_block(mods[options.modulation], options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" sb = senseblock() freq_list = [] packet_list = [] #Initialise tb = my_top_block(mods[options.modulation], options) tb.start() # start flow graph #Fake tranmission phase, to provoke opponent attacks payload_fake = struct.pack('!H', 666 & 0xffff) + "Qamazing team, if we lose handshake freq we are done for!" for i in range(0, 4000): send_pkt(payload_fake) sys.stderr.write('.') #Sense and fuzz phase tb.lock() time.sleep(2) sb.start() freq_list = sense_loop(sb) for i in range(0,1000): fuzz_result = fuzz_target(freq_list) print "Sensing complete, stoping senseblock, prepare to fuzz" sb.stop() sb.wait() tb.unlock() if fuzz_result != 0: options.tx_freq= fuzz_result sink = uhd_transmitter(options.args, symbol_rate2, options.samples_per_symbol, options.tx_freq, options.lo_offset, options.tx_gain, options.spec, options.antenna, options.clock_source, options.verbose) txpath = transmit_path(modulator2, options) for i in range(0, 4000): send_pkt(payload_fake) sys.stderr.write('.') else: time.sleep(1) print "Did not find fuzz targets" time.sleep(2) print "Fuzzing phase complete" #Initial sense and then send the result at handshake freq tb.lock() sb.start() freq_list = sense_loop(sb) while True : bin_results = find_hole(freq_list) if bin_results != 0 : break; middle_bin = int(((bin_results[1]-bin_results[0])/2) + bin_results[0]) print "Sensing complete, stoping senseblock preparation" sb.stop() sb.wait() tb.unlock() #Jump to handshake freq options.tx_freq=2362000000 sink = uhd_transmitter(options.args, symbol_rate2, options.samples_per_symbol, options.tx_freq, options.lo_offset, options.tx_gain, options.spec, options.antenna, options.clock_source, options.verbose) txpath = transmit_path(modulator2, options) #Special pktno to distinguish sensing packets number = 3333 #Set new transmit freq to midpoint of discovered window new_freq = str((middle_bin*27902) + 2357500000.0) payload_sense = struct.pack('!H', number & 0xffff) + new_freq #Send a large number of sensing packets (may change if ACK is developed), and then jump #to new freq for i in range(0, 2000): send_pkt(payload_sense) time.sleep(1) options.tx_freq=(middle_bin*27902) + 2357500000.0 sink = uhd_transmitter(options.args, symbol_rate2, options.samples_per_symbol, options.tx_freq, options.lo_offset, options.tx_gain, options.spec, options.antenna, options.clock_source, options.verbose) txpath = transmit_path(modulator2, options) #Main transmit phase # generate and send packets nbytes = int(1e6 * options.megabytes) n = 0 pktno = 0 pkt_size = int(options.size) # connect to server if options.server: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_address = ('10.0.0.200', 50000) print >>sys.stderr, 'connecting to %s port %s' % server_address sock.connect(server_address) while pktno <= 1000 and options.server: #print "nbytes :%s , pkt_size : %s , n : %s " %(nbytes, pkt_size, n) if options.server: data = ""; while len(data) < pkt_size: data += sock.recv(pkt_size - len(data)) if data == '': # No more data received from server sock.close() break; elif options.from_file is None: data = (pkt_size - 2) * chr(pktno & 0xff) else: data = source_file.read(pkt_size - 2) pktno+=1 packet_list.append(data) #Send packets in bursts of 100 or 165 and then sense again #Repeat process, until end of expirement loop_check = True while(1): for i in range(0, len(packet_list)): data=packet_list[i] payload = struct.pack('!H', i & 0xffff) + data send_pkt(payload) sys.stderr.write('.') #Alternate 2 loops, so that the system jumps at different packet numbers #This is to ensure, we dont lose packets due to transmitter jumping slightly faster if i % 100 == 0 and i > 0 and loop_check: tb.lock() sb.start() freq_list = sense_loop(sb) while True : bin_results = find_hole(freq_list) if bin_results != 0 : break; middle_bin = int(((bin_results[1]-bin_results[0])/2) + bin_results[0]) print "Sensing complete, stoping senseblock main" sb.stop() sb.wait() tb.unlock() number = 3333 new_freq = str((middle_bin*27902) + 2357500000.0) payload_sense = struct.pack('!H', number & 0xffff) + new_freq for i in range(0, 2000): send_pkt(payload_sense) time.sleep(1) options.tx_freq=(middle_bin*27902) + 2357500000.0 sink = uhd_transmitter(options.args, symbol_rate2, options.samples_per_symbol, options.tx_freq, options.lo_offset, options.tx_gain, options.spec, options.antenna, options.clock_source, options.verbose) txpath = transmit_path(modulator2, options) elif i % 165 == 0 and i > 0 and not loop_check: tb.lock() sb.start() freq_list = sense_loop(sb) while True : bin_results = find_hole(freq_list) if bin_results != 0 : break; middle_bin = int(((bin_results[1]-bin_results[0])/2) + bin_results[0]) print "Sensing complete, stoping senseblock main" sb.stop() sb.wait() tb.unlock() number = 3333 new_freq = str((middle_bin*27902) + 2357500000.0) payload_sense = struct.pack('!H', number & 0xffff) + new_freq for i in range(0, 2000): send_pkt(payload_sense) time.sleep(1) options.tx_freq=(middle_bin*27902) + 2357500000.0 sink = uhd_transmitter(options.args, symbol_rate2, options.samples_per_symbol, options.tx_freq, options.lo_offset, options.tx_gain, options.spec, options.antenna, options.clock_source, options.verbose) txpath = transmit_path(modulator2, options) loop_check = not(loop_check) send_pkt(eof=True) tb.wait() # wait for it to finish
def main(): parser = OptionParser (option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=['bpsk', 'qpsk'], default='bpsk', help="Select modulation from: bpsk, qpsk [default=%%default]") parser.add_option("-v","--verbose", action="store_true", default=False) expert_grp.add_option("-c", "--carrier-threshold", type="eng_float", default=30, help="set carrier detect threshold (dB) [default=%default]") expert_grp.add_option("","--tun-device-filename", default="/dev/net/tun", help="path to tun device file [default=%default]") digital.ofdm_mod.add_options(parser, expert_grp) digital.ofdm_demod.add_options(parser, expert_grp) transmit_path.add_options(parser, expert_grp) receive_path.add_options(parser, expert_grp) uhd_receiver.add_options(parser) uhd_transmitter.add_options(parser) (options, args) = parser.parse_args () if len(args) != 0: parser.print_help(sys.stderr) sys.exit(1) if options.rx_freq is None or options.tx_freq is None: sys.stderr.write("You must specify -f FREQ or --freq FREQ\n") parser.print_help(sys.stderr) sys.exit(1) # open the TUN/TAP interface (tun_fd, tun_ifname) = open_tun_interface(options.tun_device_filename) # Attempt to enable realtime scheduling r = gr.enable_realtime_scheduling() if r == gr.RT_OK: realtime = True else: realtime = False print "Note: failed to enable realtime scheduling" # instantiate the MAC mac = cs_mac(tun_fd, verbose=True) # build the graph (PHY) tb = my_top_block(mac.phy_rx_callback, options) mac.set_flow_graph(tb) # give the MAC a handle for the PHY print "modulation: %s" % (options.modulation,) print "freq: %s" % (eng_notation.num_to_str(options.tx_freq)) tb.rxpath.set_carrier_threshold(options.carrier_threshold) print "Carrier sense threshold:", options.carrier_threshold, "dB" print print "Allocated virtual ethernet interface: %s" % (tun_ifname,) print "You must now use ifconfig to set its IP address. E.g.," print print " $ sudo ifconfig %s 192.168.200.1" % (tun_ifname,) print print "Be sure to use a different address in the same subnet for each machine." print tb.start() # Start executing the flow graph (runs in separate threads) mac.main_loop() # don't expect this to return... tb.stop() # but if it does, tell flow graph to stop. tb.wait() # wait for it to finish
def main(): # Send packet function def send_pkt(payload='', eof=False): return tb.txpath.send_pkt(payload, eof) # Modulation initialization mods = digital.modulation_utils.type_1_mods() # Get user inputs parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='psk', help="Select modulation from: %s [default=%%default]" % (', '.join(mods.keys()),)) parser.add_option("-s", "--size", type="eng_float", default=1500, help="set packet size [default=%default]") parser.add_option("-M", "--megabytes", type="eng_float", default=1.0, help="set megabytes to transmit [default=%default]") parser.add_option("","--discontinuous", action="store_true", default=False, help="enable discontinous transmission (bursts of 5 packets)") parser.add_option("","--from-file", default=None, help="use intput file for packet contents") parser.add_option("","--to-file", default=None, help="Output file for modulated samples") # Send options selected by user to transmit_path file transmit_path.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) # Pass options selected to all modulator file (dbpsk, d8psk, dqpsk, gmsk...) for mod in mods.values(): mod.add_options(expert_grp) # Parse command-line for errors (options, args) = parser.parse_args () # Print errors and exit if len(args) != 0: parser.print_help() sys.exit(1) # Open the file which user wants to transmit if options.from_file is not None: source_file = open(options.from_file, 'r') # build the graph # Constructing transmission flowgraph and pass pointer to variable called "tb" tb = my_top_block(mods[options.modulation], options)#--> got to def my_top_block # Enable realtime scheduling r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" # Start construction of flowgraph tb.start() # start flow graph # generate and send packets nbytes = int(1e6 * options.megabytes) # Total byte to send, From command-line n = 0 # pktno = 0 # First packet number pkt_size = int(options.size) #Size of packet # send packets/file while n < nbytes: print "Sending: "+str(n)+"| bytes: "+str(nbytes)+ " | Packet Size: "+str(pkt_size) if options.from_file is None:# Generate packet (if raw data transmission chosen) data = (pkt_size - 2) * chr(pktno & 0xff) else: # Generate packet (if data from file is chosen) data = source_file.read(pkt_size - 2) if data == '': break; payload = struct.pack('!H', pktno & 0xffff) + data # Construct packet, the easy way send_pkt(payload) # Send packet through send_pkt function --> see def send_pkt() n += len(payload) sys.stderr.write('.') # If discontinues is selected then after a 4 byte send pause 1 second (Conjestion problem hack) if options.discontinuous and pktno % 5 == 4: time.sleep(1) pktno += 1 # Tell send function that we are done sending send_pkt(eof=True) # Keep running flowgraph until user kills it tb.wait() # wait for it to finish
def main(): def send_pkt(payload='', eof=False): return tb.txpath.send_pkt(payload, eof) mods = digital.modulation_utils.type_1_mods() parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='psk', help="Select modulation from: %s [default=%%default]" % (', '.join(mods.keys()),)) parser.add_option("-s", "--size", type="eng_float", default=1500, help="set packet size [default=%default]") parser.add_option("-M", "--megabytes", type="eng_float", default=1.0, help="set megabytes to transmit [default=%default]") parser.add_option("","--discontinuous", action="store_true", default=False, help="enable discontinous transmission (bursts of 5 packets)") parser.add_option("","--from-file", default=None, help="use intput file for packet contents") parser.add_option("","--to-file", default=None, help="Output file for modulated samples") transmit_path.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) for mod in mods.values(): mod.add_options(expert_grp) (options, args) = parser.parse_args () if len(args) != 0: parser.print_help() sys.exit(1) if options.from_file is not None: source_file = open(options.from_file, 'r') # build the graph tb = my_top_block(mods[options.modulation], options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() # start flow graph # generate and send packets nbytes = int(1e6 * options.megabytes) n = 0 pktno = 0 pkt_size = int(options.size) while n < nbytes: if options.from_file is None: data = (pkt_size - 2) * chr(pktno & 0xff) else: data = source_file.read(pkt_size - 2) if data == '': break; payload = struct.pack('!H', pktno & 0xffff) + data send_pkt(payload) n += len(payload) sys.stderr.write('.') if options.discontinuous and pktno % 1 == 0: time.sleep(0.01) pktno += 1 send_pkt(eof=True) tb.wait() # wait for it to finish
def main(): mods = digital.modulation_utils.type_1_mods() demods = digital.modulation_utils.type_1_demods() parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='gmsk', help="Select modulation from: %s [default=%%default]" % (', '.join(mods.keys()), )) parser.add_option("-s", "--size", type="eng_float", default=1500, help="set packet size [default=%default]") parser.add_option("-v", "--verbose", action="store_true", default=False) expert_grp.add_option( "-c", "--carrier-threshold", type="eng_float", default=30, help="set carrier detect threshold (dB) [default=%default]") expert_grp.add_option("", "--tun-device-filename", default="/dev/net/tun", help="path to tun device file [default=%default]") transmit_path.add_options(parser, expert_grp) receive_path.add_options(parser, expert_grp) uhd_receiver.add_options(parser) uhd_transmitter.add_options(parser) for mod in mods.values(): mod.add_options(expert_grp) for demod in demods.values(): demod.add_options(expert_grp) (options, args) = parser.parse_args() if len(args) != 0: parser.print_help(sys.stderr) sys.exit(1) # open the TUN/TAP interface #(tun_fd, tun_ifname) = open_tun_interface(options.tun_device_filename) if options.rx_freq is None or options.tx_freq is None: sys.stderr.write("You must specify -f FREQ or --freq FREQ\n") parser.print_help(sys.stderr) sys.exit(1) # get a Spinal instance spinal = Spinal(experimentSpec, numpy.random.RandomState().tomaxint(4), 3) # Attempt to enable realtime scheduling r = gr.enable_realtime_scheduling() if r == gr.RT_OK: realtime = True else: realtime = False print "Note: failed to enable realtime scheduling" # instantiate the MAC #mac = cs_mac(tun_fd, verbose=True) mac = cs_mac(spinal, verbose=True) # build the graph (PHY) tb = my_top_block(mods[options.modulation], demods[options.modulation], mac.phy_rx_callback, options) mac.set_top_block(tb) # give the MAC a handle for the PHY if tb.txpath.bitrate() != tb.rxpath.bitrate(): print "WARNING: Transmit bitrate = %sb/sec, Receive bitrate = %sb/sec" % ( eng_notation.num_to_str(tb.txpath.bitrate()), eng_notation.num_to_str(tb.rxpath.bitrate())) print "modulation: %s" % (options.modulation, ) print "freq: %s" % (eng_notation.num_to_str(options.tx_freq)) print "bitrate: %sb/sec" % (eng_notation.num_to_str( tb.txpath.bitrate()), ) print "samples/symbol: %3d" % (tb.txpath.samples_per_symbol(), ) tb.rxpath.set_carrier_threshold(options.carrier_threshold) print "Carrier sense threshold:", options.carrier_threshold, "dB" source_file = open('./test.264', 'r') #print 'zhifeng: from file' #print 'source_file = ', source_file file_data = source_file.read() file_length = len(file_data) #print "file length is", file_length #print file_data #raw_input('zhifeng on 070928: press any key to continue') source_file.close() tb.start() # Start executing the flow graph (runs in separate threads) print "Packet length for spinal codes: %d" % experimentSpec['packetGen'][ 'length'] mac.main_loop(file_data, experimentSpec['packetGen']['length'] / 8) # don't expect this to return... tb.stop() # but if it does, tell flow graph to stop. tb.wait() # wait for it to finish
def main(): def update(): conn = psy.connect(database="spectrum", user="******", password="******", host="192.168.0.201", port="5432") #conn = psy.connect(database="spectrum",user="******",password="******",host="140.112.21.120",port="9527") cur = conn.cursor(cursor_factory=ex.RealDictCursor) cur.execute( "UPDATE local_incumbents SET ms_sens = '1' WHERE name = 'TTCzone' AND band_id='41' AND contact_name = '01' ;" ) conn.commit() cur.close() conn.close() def rx_callback(ok, payload): global pktno, pktno_receive if ok: #if payload[0] == 'B': # print '\t'+"receiving beacon" + payload[0:] if payload[0] == 'A': #ack from beacon myPay.pause() myPay.type = 1 myPay.restart() #print '\t'+"receiving ack from beacon" ''' elif payload[0] == 'a': #ack from data myPay.pause() for n in range(1,4): pktno_receive = pktno_receive + payload[n] if pktno == int(pktno_receive): myPay.retry = 0 else: myPay.retry = 1 myPay.restart() print '\t'+"receiving ack from data" + payload[1:4] elif payload[0] == 'F': print "missino completed" ''' #print "\n" parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("", "--discontinuous", action="store_true", default=True, help="enable discontinuous") parser.add_option("-M", "--megabytes", type="eng_float", default=1.0, help="set megabytes to transmit [default=%default]") parser.add_option("", "--from-file", default=None, help="input file of samples to demod") parser.add_option("-s", "--size", type="eng_float", default=400, help="set packet size [default=%default]") receive_path.add_options(parser, expert_grp) uhd_receiver.add_options(parser) digital.ofdm_demod.add_options(parser, expert_grp) transmit_path.add_options(parser, expert_grp) digital.ofdm_mod.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) (options, args) = parser.parse_args() if options.from_file is None: if options.rx_freq is None: sys.stderr.write("You must specify -f FREQ or --freq FREQ\n") parser.print_help(sys.stderr) sys.exit(1) # build the graph(PHY) tb = my_top_block(rx_callback, options) lock = threading.Lock() myPay = payload_mgr(tb, lock, "thread", datetime.datetime.now(), "source_file") myPay.start() r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() # start flow graph count_detect = 0 if_update = 0 myPay.channl_hopping_by_modifing_mine_database("2301") while True: #print'f**k' #???bout.waitime = -1 #global rx_callback_enable, trans_status, get_ack, randombackoff, ttRB, difscount, DIFS #trans_status = 0 #at the new frame, start with a beacon #rx_callback_enable = 0 time.sleep(0.499) #myPay.query_database() myPay.pause() time.sleep(0.001) detection = myPay.feature_detect #print 'detection result' #print detection if detection == 1: count_detect += 1 else: count_detect = 0 #update() if count_detect > 1 and if_update == 0: print "Primary user is present... start..." print 'update to the database' update() tb.set_tx_freq(600e6) tb.set_rx_freq(600e6) myPay.channl_hopping_by_modifing_mine_database( "41") #41 is 600MHz (means that stop transmission) if_update = 1 count_detect = 0 break myPay.reset() myPay.notification_for_primary(detection) myPay.pause() myPay.reset() myPay.startSlot = datetime.datetime.now() myPay.restart() #??? time.sleep(0.010) #wait 10ms to detect #??? FreCtrl.printSpace() feel that is not necessary #print "ack status=", get_ack #if (tb.rxpath.variable_function_probe_0 == 0): #frequency assigned by controller # print "TV is absent... start..." #???bout.set_waitime() # rx_callback_enable = 1 #the right timing to receive #time.sleep(hop_interval/1000) #else: # print "TV is present...wait..." # FreCtrl.set_frequency(tb) #???rx_callback_enable = not bool(tb.rxpath.variable_function_probe_0) '''
def main(): print "ssma.py" global n_right n_right = 0 start_time = time.time() print "Start Time " , start_time parser = OptionParser (option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=['bpsk', 'qpsk'], default='bpsk', help="Select modulation from: bpsk, qpsk [default=%%default]") expert_grp.add_option("-c", "--carrier-threshold", type="eng_float", default=40, help="set carrier detect threshold (dB) [default=%default]") expert_grp.add_option("", "--nc-filter", action="store_true", default=False) parser.add_option("-v","--verbose", action="store_true", default=False) # linklab, add option to indicate sender or receiver parser.add_option("-s","--sender", action="store_true", default=False) parser.add_option("-r","--receiver", action="store_true", default=False) usrp_graph.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) #uhd_receiver.add_options(parser) transmit_path.add_options(parser, expert_grp) receive_path.add_options(parser, expert_grp) gr_papyrus.ofdm.ofdm_mod.add_options(parser, expert_grp) gr_papyrus.ofdm.ofdm_demod.add_options(parser, expert_grp) (options, args) = parser.parse_args () options.carrier_map = SYNC_MAP print "Added options" print options if len(args) != 0: parser.print_help(sys.stderr) sys.exit(1) if options.rx_freq is None or options.tx_freq is None: print ("You must specify -f FREQ or --freq FREQ\n") parser.print_help(sys.stderr) sys.exit(1) # linklab, check if the current node is either a sender or a receiver if options.sender and options.receiver: print ("You cannot specify both sender and receiver\n") sys.exit(1) if (not options.sender) and (not options.receiver): print ("You must specify either sender or receiver\n") sys.exit(1) # # Attempt to enable realtime scheduling r = gr.enable_realtime_scheduling() if r == gr.RT_OK: realtime = True else: realtime = False print "Note: failed to enable realtime scheduling" # instantiate the MAC # linklab, use ssma instead of csma mac = ss_mac(options.sender, start_time, verbose=options.verbose) print "RX frequency", options.rx_freq print "TX frequency", options.tx_freq # build the graph (PHY) tb = usrp_graph(mac.ReceivePacket, options) print "returned from usrp_graph" mac.set_flow_graph(tb) # give the MAC a handle for the PHY #if fg.txpath.bitrate() != fg.rxpath.bitrate(): # print "WARNING: Transmit bitrate = %sb/sec, Receive bitrate = %sb/sec" % ( # eng_notation.num_to_str(fg.txpath.bitrate()), # eng_notation.num_to_str(fg.rxpath.bitrate())) print "modulation: %s" % (options.modulation,) print "freq: %s" % (eng_notation.num_to_str(options.tx_freq)) # print "bitrate: %sb/sec" % (eng_notation.num_to_str(tb.txpath.bitrate()),) # print "samples/symbol: %3d" % (tb.txpath.samples_per_symbol(),) # print "interp: %3d" % (tb.txpath.interp(),) # print "decim: %3d" % (tb.rxpath.decim(),) tb.start() # Start executing the flow graph (runs in separate threads) mac.main_loop() # don't expect this to return...
def main(): def send_pkt(payload='', eof=False): return tb.txpath.send_pkt(payload, eof) mods = digital.modulation_utils.type_1_mods() parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='dqpsk', help="Select modulation from: %s [default=%%default]" % (', '.join(mods.keys()),)) # parser.add_option("-s", "--size", type="eng_float", default=1442, # help="set packet size [default=%default]") # parser.add_option("-M", "--megabytes", type="eng_float", default=1.0, # help="set megabytes to transmit [default=%default]") parser.add_option("","--discontinuous", action="store_true", default=False, help="enable discontinous transmission (bursts of 5 packets)") parser.add_option("","--from-file", default=None, help="use intput file for packet contents") parser.add_option("","--to-file", default=None, help="Output file for modulated samples") transmit_path.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) for mod in mods.values(): mod.add_options(expert_grp) (options, args) = parser.parse_args () if len(args) != 0: parser.print_help() sys.exit(1) if options.from_file is not None: source_file = open(options.from_file, 'r') # build the graph tb = my_top_block(mods[options.modulation], options) ftb = filter_top_block(options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() # start flow graph ftb.start() # log parameter to OML cmd1 = "/root/OML/omlcli --out h2_benchmark --line \"" cmd1 = cmd1 + " tx-freq=" + str(options.tx_freq) cmd1 = cmd1 + " modulation=" + str(options.modulation) cmd1 = cmd1 + " tx-gain=" + str(options.tx_gain) cmd1 = cmd1 + " bitrate=" + str(options.bitrate) cmd1 = cmd1 + " sps=" + str(options.samples_per_symbol) cmd1 = cmd1 + "\"" from subprocess import os os.system(cmd1) # Fetch packets from server s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.settimeout(10) TCP_IP='10.10.0.51' TCP_PORT=5123 try: s.connect((TCP_IP, TCP_PORT)) except socket.timeout: print"Connection timed out, try again later" return except socket.error: print"Connection error" return print "Setting frequency to %d\n" % (options.tx_freq+625000) tb.sink.set_freq(options.tx_freq+625000) n = 0 pktno = 0 pkt_size = int(1442) MESSAGE = struct.pack('!l',pkt_size-2) while 1: #n < nbytes: if options.from_file is None: try: s.send(MESSAGE) data=s.recv(pkt_size-2) except socket.timeout: print"Connection timed out, try again later" return except socket.error: print"Connection closed" return if data.__len__() < 8: print "Connection timed out, try again later" break if options.verbose: # First 4 bytes are checksum followed by the 4 byte sequence number crc,sn = struct.unpack('!LL',data[:8]) print "Seq #:", sn, " with CRC [", hex(crc), "]" else: data = source_file.read(pkt_size - 2) if data == '': break; payload = struct.pack('!H', pktno & 0xffff) + data send_pkt(payload) n += len(payload) sys.stderr.write('.') if options.discontinuous and pktno % 5 == 4: time.sleep(1) if pktno % 25 == 25-1: tb.sink.set_gain(-60) time.sleep(0.250) low_sum = ftb.probe_lp.level() high_sum = ftb.probe_hp.level() #while 1: #time.sleep(0.1) #low_sum = ftb.probe_lp.level() #high_sum = ftb.probe_hp.level() #print " low=%f\nhigh=%f\n" % (low_sum*100000, high_sum*100000) print "\n low=%f\nhigh=%f\n" % (low_sum*100000, high_sum*100000) if low_sum > high_sum: print "Setting frequency to %d\n" % (options.tx_freq+625000) tb.sink.set_freq(options.tx_freq+625000) else: print "Setting frequency to %d\n" % (options.tx_freq-625000) tb.sink.set_freq(options.tx_freq-625000) tb.sink.set_gain(30) #if pktno % 50 == 50-1: # print "Setting frequency to %d\n" % (options.tx_freq+625000) #tb.sink.set_freq(options.tx_freq+625000) pktno += 1 if options.from_file is None: s.close() time.sleep(5) send_pkt(eof=True) tb.wait() # wait for it to finish
def main(): print "ssma.py" global n_right n_right = 0 start_time = time.time() print "Start Time ", start_time parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option( "-m", "--modulation", type="choice", choices=['bpsk', 'qpsk'], default='bpsk', help="Select modulation from: bpsk, qpsk [default=%%default]") expert_grp.add_option( "-c", "--carrier-threshold", type="eng_float", default=40, help="set carrier detect threshold (dB) [default=%default]") expert_grp.add_option("", "--nc-filter", action="store_true", default=False) parser.add_option("-v", "--verbose", action="store_true", default=False) # linklab, add option to indicate sender or receiver parser.add_option("-s", "--sender", action="store_true", default=False) parser.add_option("-r", "--receiver", action="store_true", default=False) usrp_graph.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) #uhd_receiver.add_options(parser) transmit_path.add_options(parser, expert_grp) receive_path.add_options(parser, expert_grp) gr_papyrus.ofdm.ofdm_mod.add_options(parser, expert_grp) gr_papyrus.ofdm.ofdm_demod.add_options(parser, expert_grp) (options, args) = parser.parse_args() options.carrier_map = SYNC_MAP print "Added options" print options if len(args) != 0: parser.print_help(sys.stderr) sys.exit(1) if options.rx_freq is None or options.tx_freq is None: print("You must specify -f FREQ or --freq FREQ\n") parser.print_help(sys.stderr) sys.exit(1) # linklab, check if the current node is either a sender or a receiver if options.sender and options.receiver: print("You cannot specify both sender and receiver\n") sys.exit(1) if (not options.sender) and (not options.receiver): print("You must specify either sender or receiver\n") sys.exit(1) # # Attempt to enable realtime scheduling r = gr.enable_realtime_scheduling() if r == gr.RT_OK: realtime = True else: realtime = False print "Note: failed to enable realtime scheduling" # instantiate the MAC # linklab, use ssma instead of csma mac = ss_mac(options.sender, start_time, verbose=options.verbose) print "RX frequency", options.rx_freq print "TX frequency", options.tx_freq # build the graph (PHY) tb = usrp_graph(mac.ReceivePacket, options) print "returned from usrp_graph" mac.set_flow_graph(tb) # give the MAC a handle for the PHY #if fg.txpath.bitrate() != fg.rxpath.bitrate(): # print "WARNING: Transmit bitrate = %sb/sec, Receive bitrate = %sb/sec" % ( # eng_notation.num_to_str(fg.txpath.bitrate()), # eng_notation.num_to_str(fg.rxpath.bitrate())) print "modulation: %s" % (options.modulation, ) print "freq: %s" % (eng_notation.num_to_str(options.tx_freq)) # print "bitrate: %sb/sec" % (eng_notation.num_to_str(tb.txpath.bitrate()),) # print "samples/symbol: %3d" % (tb.txpath.samples_per_symbol(),) # print "interp: %3d" % (tb.txpath.interp(),) # print "decim: %3d" % (tb.rxpath.decim(),) tb.start() # Start executing the flow graph (runs in separate threads) mac.main_loop() # don't expect this to return...
def main(): def send_pkt(payload='', eof=False, timeValid=False, timestamp=0): if eof: msg = gr.message(1) else: msg = gr.message_from_string(payload) if timeValid: secs = long(timestamp) frac_secs = timestamp - long(timestamp) msg.set_timestamp(secs, frac_secs) return tb.txpath.msgq().insert_tail(msg) parser = OptionParser(option_class=eng_option, conflict_handler="resolve") parser.add_option("-n", "--num", type="eng_float", default=1, help="set number of packets [default=%default]") parser.add_option( "-r", "--repeat", action="store_true", default=False, help="repeat transmitting the file or not [default=%default]") parser.add_option("", "--data-file", default=None, help="use complex input file for transmission") parser.add_option("", "--to-file", default=None, help="Output file for modulated samples") parser.add_option("-W", "--bandwidth", type="eng_float", default=4e6, help="set symbol bandwidth [default=%default]") parser.add_option( "", "--amp", type="eng_float", default=1, help="set gain factor for complex baseband floats [default=%default]") #transmit_path.add_options(parser, expert_grp) #digital.ofdm_mod.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) (options, args) = parser.parse_args() # build the graph tb = my_top_block(options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" if options.repeat: print "Files will be repeatly transmit." tb.start() # start flow graph ########################################################################### if options.data_file is None: sys.stderr.write("You must specify data file\n") parser.print_help(sys.stderr) sys.exit(1) print "End of Tx ..." time.sleep(1) ########################################################################### tb.wait() # wait for it to finish
def main(): def send_pkt(payload='', timestamp=None, eof=False): if eof: msg = gr.message(1) else: msg = gr.message_from_string(payload) if timestamp is not None: secs = long(timestamp) frac_secs = timestamp - long(timestamp) msg.set_timestamp(secs, frac_secs) return tb.txpath.msgq().insert_tail(msg) parser = OptionParser(option_class=eng_option, conflict_handler="resolve") parser.add_option("-n", "--num", type="eng_float", default=1, help="set number of packets [default=%default]") parser.add_option("-g", "--gap", type="eng_float", default=0.005, help="set number of packets [default=%default]") parser.add_option("","--data-file", default=None, help="use complex input file for transmission") parser.add_option("","--to-file", default=None, help="Output file for modulated samples") parser.add_option("-W", "--bandwidth", type="eng_float", default=4e6, help="set symbol bandwidth [default=%default]") parser.add_option("", "--amp", type="eng_float", default=0.1, help="set gain factor for complex baseband floats [default=%default]") parser.add_option("", "--time", action="store_true", default=False, help="set timed tx mode") #transmit_path.add_options(parser, expert_grp) #digital.ofdm_mod.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) (options, args) = parser.parse_args () # build the graph tb = my_top_block(options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() # start flow graph ########################################################################### if options.data_file is None: sys.stderr.write("You must specify data file\n") parser.print_help(sys.stderr) sys.exit(1) MAX_READ_BYTES = 1000000000 file_object = open(options.data_file) data = file_object.read(MAX_READ_BYTES) print "Length of payload = ", len(data), " | MAX_READ = ", MAX_READ_BYTES file_object.close() secs, frac = tb.sink.get_usrp_time() print "USRP Time: ", secs cnt = 0 GAP = options.gap startTime = secs+0.1 while cnt < options.num: if options.time: send_pkt(data, startTime+cnt*GAP, eof=False) else: send_pkt(data, eof=False) if (options.gap > 0.0): sys.stdout.flush() time.sleep(options.gap) #print "Send pkt no.", cnt cnt = cnt + 1 send_pkt(eof=True) print "End of Tx | cnt = ", cnt time.sleep(1) ########################################################################### tb.wait() # wait for it to finish
def main(): mods = digital.modulation_utils.type_1_mods() demods = digital.modulation_utils.type_1_demods() parser = OptionParser (option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='gmsk', help="Select modulation from: %s [default=%%default]" % (', '.join(mods.keys()),)) parser.add_option("-s", "--size", type="eng_float", default=1500, help="set packet size [default=%default]") parser.add_option("-v","--verbose", action="store_true", default=False) expert_grp.add_option("-c", "--carrier-threshold", type="eng_float", default=30, help="set carrier detect threshold (dB) [default=%default]") expert_grp.add_option("","--tun-device-filename", default="/dev/net/tun", help="path to tun device file [default=%default]") transmit_path.add_options(parser, expert_grp) receive_path.add_options(parser, expert_grp) uhd_receiver.add_options(parser) uhd_transmitter.add_options(parser) for mod in mods.values(): mod.add_options(expert_grp) for demod in demods.values(): demod.add_options(expert_grp) (options, args) = parser.parse_args () if len(args) != 0: parser.print_help(sys.stderr) sys.exit(1) # open the TUN/TAP interface (tun_fd, tun_ifname) = open_tun_interface(options.tun_device_filename) # Attempt to enable realtime scheduling r = gr.enable_realtime_scheduling() if r == gr.RT_OK: realtime = True else: realtime = False print "Note: failed to enable realtime scheduling" # instantiate the MAC mac = cs_mac(tun_fd, verbose=True) # build the graph (PHY) tb = my_top_block(mods[options.modulation], demods[options.modulation], mac.phy_rx_callback, options) mac.set_top_block(tb) # give the MAC a handle for the PHY if tb.txpath.bitrate() != tb.rxpath.bitrate(): print "WARNING: Transmit bitrate = %sb/sec, Receive bitrate = %sb/sec" % ( eng_notation.num_to_str(tb.txpath.bitrate()), eng_notation.num_to_str(tb.rxpath.bitrate())) print "modulation: %s" % (options.modulation,) print "freq: %s" % (eng_notation.num_to_str(options.tx_freq)) print "bitrate: %sb/sec" % (eng_notation.num_to_str(tb.txpath.bitrate()),) print "samples/symbol: %3d" % (tb.txpath.samples_per_symbol(),) tb.rxpath.set_carrier_threshold(options.carrier_threshold) print "Carrier sense threshold:", options.carrier_threshold, "dB" print print "Allocated virtual ethernet interface: %s" % (tun_ifname,) print "You must now use ifconfig to set its IP address. E.g.," print print " $ sudo ifconfig %s 192.168.200.1" % (tun_ifname,) print print "Be sure to use a different address in the same subnet for each machine." print tb.start() # Start executing the flow graph (runs in separate threads) mac.main_loop() # don't expect this to return... tb.stop() # but if it does, tell flow graph to stop. tb.wait() # wait for it to finish
def main(): global n_rcvd, n_right, v_frame, mean_delta, next_tx_ts, stop_rx_ts, ps_end_ts, alloc_index, vf_index,\ listen_only_to n_rcvd = 0 n_right = 0 mean_delta = 0 next_tx_ts = 0 stop_rx_ts = 0 ps_end_ts = 0 alloc_index = -1 vf_index = -1 listen_only_to = [] wrong_pktno = 0xFF00 v_frame = '' vf_len = 8 ps_model = PerfectScheme(PacketType.PS_BROADCAST.index, PacketType.PS_PKT.index, NODE_SLOT_TIME) vfs_model = VirtualFrameScheme(PacketType.VFS_BROADCAST.index, PacketType.VFS_PKT.index, NODE_SLOT_TIME) def send_beacon_pkt(my_tb, pkt_size, pkt_no): # BS only # payload = prefix + now + beacon + dummy payload_prefix = struct.pack('!H', pkt_no & 0xffff) beacon = struct.pack('!H', PacketType.BEACON.index & 0xffff) data_size = len(payload_prefix) + TIMESTAMP_LEN + len(beacon) dummy = (pkt_size - data_size) * chr(pkt_no & 0xff) now_timestamp = my_tb.sink.get_time_now().get_real_secs() now_timestamp_str = '{:.3f}'.format(now_timestamp) payload = payload_prefix + now_timestamp_str + beacon + dummy my_tb.txpath.send_pkt(payload) logger.info("{} broadcast BEACON - {}".format( str(datetime.fromtimestamp(now_timestamp)), pkt_no)) # Deprecated # def send_resp_beacon_pkt(my_tb, pkt_size, pkt_no): # Node only # # payload = prefix + now + respond_beacon + node_id + dummy # # payload_prefix = struct.pack('!H', pkt_no & 0xffff) # respond_beacon = struct.pack('!H', PacketType.RESPOND_BEACON.index & 0xffff) # data_size = len(payload_prefix) + TIMESTAMP_LEN + len(respond_beacon) + NODE_ID_LEN # dummy = (pkt_size - data_size) * chr(pkt_no & 0xff) # now_timestamp = my_tb.sink.get_time_now().get_real_secs() # now_timestamp_str = '{:.3f}'.format(now_timestamp) # payload = payload_prefix + now_timestamp_str + respond_beacon + NODE_ID + dummy # my_tb.txpath.send_pkt(payload) # logger.info("{} send RESPOND_BEACON - {}".format(str(datetime.fromtimestamp(now_timestamp)), pkt_no)) # # # TODO: how to track rtt? # # Keep rtt_list size limit # rtt_list.append(now_timestamp) # if len(rtt_list) > MAX_RTT_AMT: # rtt_list.pop(0) def do_every_beacon(interval, _send_pkt_func, my_tb, pkt_size, max_pkt_amt, iteration=1): # For other functions to check these variables global my_thread, my_iteration my_iteration = iteration if iteration < max_pkt_amt: # my_thread = threading.Timer(interval, do_every_beacon, # [interval, _send_pkt_func, my_tb, pkt_amt, 0 # if iteration == 0 else iteration + 1]) my_thread = threading.Timer(interval, do_every_beacon, [ interval, _send_pkt_func, my_tb, pkt_size, max_pkt_amt, max_pkt_amt if iteration >= max_pkt_amt else iteration + 1 ]) my_thread.start() # execute func _send_pkt_func(my_tb, pkt_size, iteration) def do_every_protocol_bs(interval, _send_pkt_func, my_tb, pkt_size, node_amt, max_pkt_amt, iteration=1): # For other functions to check these variables global my_thread, my_iteration my_iteration = iteration if iteration < max_pkt_amt: my_thread = threading.Timer(interval, do_every_protocol_bs, [ interval, _send_pkt_func, my_tb, pkt_size, node_amt, max_pkt_amt, max_pkt_amt if iteration >= max_pkt_amt else iteration + 1 ]) my_thread.start() # execute func _send_pkt_func(my_tb, pkt_size, node_amt, iteration) def do_every_protocol_node(interval, _send_pkt_func, node_id, my_tb, pkt_size, node_data, max_pkt_amt, iteration=1): # For other functions to check these variables global my_thread, my_iteration my_iteration = iteration if iteration < max_pkt_amt: my_thread = threading.Timer(interval, do_every_protocol_node, [ interval, _send_pkt_func, node_id, my_tb, pkt_size, node_data, max_pkt_amt, max_pkt_amt if iteration >= max_pkt_amt else iteration + 1 ]) my_thread.start() # execute func _send_pkt_func(node_id, my_tb, pkt_size, node_data, iteration) def rx_bs_callback(ok, payload): # For BS global n_rcvd, n_right, mean_delta, next_tx_ts, stop_rx_ts, nodes_sync_delta, listen_only_to n_rcvd += 1 (pktno, ) = struct.unpack('!H', payload[0:2]) # Filter out incorrect pkt if pktno >= wrong_pktno: logger.warning("wrong pktno {}. Drop pkt!".format(pktno)) return try: pkt_timestamp_str = payload[2:2 + TIMESTAMP_LEN] pkt_timestamp = float(pkt_timestamp_str) except: logger.warning("Timestamp {} is not a float. Drop pkt!".format( pkt_timestamp_str)) return now_timestamp = rx_tb.source.get_time_now().get_real_secs() # now_timestamp_str = '{:.3f}'.format(now_timestamp) delta = now_timestamp - pkt_timestamp # +ve: Node earlier; -ve: BS earlier if not -5 < delta < 5: logger.warning( "Delay out-of-range: {}, timestamp {}. Drop pkt!".format( delta, pkt_timestamp_str)) return (pkt_type, ) = struct.unpack( '!H', payload[2 + TIMESTAMP_LEN:2 + TIMESTAMP_LEN + 2]) # if pkt_type not in [PacketType.RESPOND_BEACON.index, PacketType.PS_PKT.index]: if pkt_type not in [PacketType.PS_PKT.index, PacketType.VFS_PKT.index]: logger.warning("Invalid pkt_type {}. Drop pkt!".format(pkt_type)) return if listen_only_to and pkt_type not in listen_only_to: str_listen_only_to = [PacketType[x].key for x in listen_only_to] logger.warning( "Interest only in pkt_type {}, not {}. Drop pkt!".format( str_listen_only_to, PacketType[pkt_type].key)) return # Deprecated # if pkt_type == PacketType.RESPOND_BEACON.index: # node_id = payload[2+TIMESTAMP_LEN+2:2+TIMESTAMP_LEN+2+NODE_ID_LEN] # if nodes_sync_delta.get(node_id) is None: # nodes_sync_delta[node_id] = [] # nodes_sync_delta[node_id].append(delta) # # Keep nodes_sync_delta in size limit # if len(nodes_sync_delta[node_id]) > MAX_DELTA_AMT: # nodes_sync_delta[node_id].pop(0) # mean_delta = numpy.mean(nodes_sync_delta[node_id]) # # next_tx_ts = now_timestamp + 0.5 - COMMAND_DELAY # # logger.info("{} BS recv RESPOND_BEACON from node {}. Node time: {}, Avg delay: {}".format( # str(datetime.fromtimestamp(now_timestamp)), node_id, str(datetime.fromtimestamp(pkt_timestamp)), # mean_delta)) # # logger.debug("Node {} len {} {}".format(node_id, len(nodes_sync_delta[node_id]), nodes_sync_delta[node_id])) # # logger.debug("Node {}: {}".format(node_id, nodes_sync_delta[node_id])) # return if pkt_type == PacketType.PS_PKT.index: for i, tpl in enumerate(ps_model.nodes_expect_time): node_id, begin_at, end_at = tpl if begin_at <= now_timestamp <= end_at: logger.info( "{} ({}) [Slot {}: Node {} Session] BS recv PS_PKT {}, data: {}" .format(str(datetime.fromtimestamp(now_timestamp)), now_timestamp, i, node_id, pktno, ps_model.get_node_data(payload))) return logger.info( "{} ({}) [No slot/session] BS recv PS_PKT {}, data: {}".format( str(datetime.fromtimestamp(now_timestamp)), now_timestamp, pktno, ps_model.get_node_data(payload))) # Last timestamp for PS_PKT session #next_tx_ts = ps_model.nodes_expect_time[-1][-1] + 0.2 # add some delay return if pkt_type == PacketType.VFS_PKT.index: for i, tpl in enumerate(vfs_model.nodes_expect_time): node_id, begin_at, end_at = tpl if begin_at <= now_timestamp <= end_at: logger.info( "{} ({}) [Slot {}: Node {} Session] BS recv VFS_PKT {}, data: {}" .format(str(datetime.fromtimestamp(now_timestamp)), now_timestamp, i, node_id, pktno, vfs_model.get_node_data(payload))) return logger.info( "{} ({}) [No slot/session] BS recv VFS_PKT {}, data: {}". format(str(datetime.fromtimestamp(now_timestamp)), now_timestamp, pktno, vfs_model.get_node_data(payload))) # Last timestamp for VFS_PKT session #next_tx_ts = vfs_model.nodes_expect_time[-1][-1] + 0.2 # add some delay return def rx_node_callback(ok, payload): # For Node global n_rcvd, n_right, mean_delta, next_tx_ts, stop_rx_ts, ps_end_ts, alloc_index, vf_index, \ listen_only_to n_rcvd += 1 (pktno, ) = struct.unpack('!H', payload[0:2]) # Filter out incorrect pkt if pktno >= wrong_pktno: logger.warning("Wrong pktno {}. Drop pkt!".format(pktno)) return try: pkt_timestamp_str = payload[2:2 + TIMESTAMP_LEN] pkt_timestamp = float(pkt_timestamp_str) except: logger.warning("Timestamp {} is not a float. Drop pkt!".format( pkt_timestamp_str)) return now_timestamp = rx_tb.source.get_time_now().get_real_secs() # now_timestamp_str = '{:.3f}'.format(now_timestamp) delta = now_timestamp - pkt_timestamp # +ve: BS earlier; -ve: Node earlier if not -5 < delta < 5: logger.warning( "Delay out-of-range: {}, timestamp {}. Drop pkt!".format( delta, pkt_timestamp_str)) return (pkt_type, ) = struct.unpack( '!H', payload[2 + TIMESTAMP_LEN:2 + TIMESTAMP_LEN + 2]) if pkt_type not in [ PacketType.BEACON.index, PacketType.ACK_RESPOND.index, PacketType.PS_BROADCAST.index, PacketType.VFS_BROADCAST.index ]: logger.warning("Invalid pkt_type {}. Drop pkt!".format(pkt_type)) return if listen_only_to and pkt_type not in listen_only_to: str_listen_only_to = [PacketType[x].key for x in listen_only_to] logger.warning( "Interest only in pkt_type {}, not {}. Drop pkt!".format( str_listen_only_to, PacketType[pkt_type].key)) return if pkt_type == PacketType.BEACON.index: delta_list.append(delta) # Keep delta_list in size limit if len(delta_list) > MAX_DELTA_AMT: delta_list.pop(0) mean_delta = numpy.mean(delta_list) # mean_delta_str = '{:07.3f}'.format(delta) # Adjust time if needed if not -0.05 <= mean_delta <= 0.05: rx_tb.source.set_time_now(uhd.time_spec(pkt_timestamp)) now_timestamp = rx_tb.source.get_time_now().get_real_secs() logger.info("Adjust time... New time: {}".format( str(datetime.fromtimestamp(now_timestamp)))) stop_rx_ts = now_timestamp + 0.5 - COMMAND_DELAY # Hack: for RX2400 if pktno >= MAX_PKT_AMT - 10: stop_rx_ts -= 0.3 logger.info( "{} Node recv BEACON {}. BS time: {}, Avg delay: {}".format( str(datetime.fromtimestamp(now_timestamp)), pktno, str(datetime.fromtimestamp(pkt_timestamp)), mean_delta)) # logger.debug("stop_rx_ts {}".format(str(datetime.fromtimestamp(stop_rx_ts)))) return if pkt_type == PacketType.PS_BROADCAST.index: node_amount = ps_model.get_node_amount(payload) seed = ps_model.get_seed(payload) alloc_index = ps_model.compute_alloc_index(node_amount, NODE_ID, seed) try: begin_timestamp_str = ps_model.get_begin_time_str(payload) begin_timestamp = float(begin_timestamp_str) except: logger.warning( "begin_timestamp {} is not a float. Drop pkt!".format( begin_timestamp_str)) return stop_rx_ts = now_timestamp + 0.4 # TODO: Duo to various delays, adjust a bit to before firing round up second next_tx_ts = begin_timestamp + (NODE_SLOT_TIME * alloc_index) - TRANSMIT_DELAY # Each node time slot at NODE_SLOT_TIME seconds ps_end_ts = begin_timestamp + (NODE_SLOT_TIME * node_amount) logger.info( "{} Node recv PS_BROADCAST {}, BS time {}, Total {}, Seed {}, Index {}, Delay {}" .format(str(datetime.fromtimestamp(now_timestamp)), pktno, str(datetime.fromtimestamp(pkt_timestamp)), node_amount, seed, alloc_index, delta)) # logger.debug("begin {}, stop_rx_ts {}, next_tx_ts {}, ps_end_ts {}".format( # str(datetime.fromtimestamp(begin_timestamp)), str(datetime.fromtimestamp(stop_rx_ts)), # str(datetime.fromtimestamp(next_tx_ts)), str(datetime.fromtimestamp(ps_end_ts)))) return if pkt_type == PacketType.VFS_BROADCAST.index: node_amount = vfs_model.get_node_amount(payload) seed = ps_model.get_seed(payload) try: begin_timestamp_str = vfs_model.get_begin_time_str(payload) begin_timestamp = float(begin_timestamp_str) except: logger.warning( "begin_timestamp {} is not a float. Drop pkt!".format( begin_timestamp_str)) return try: v_frame = vfs_model.get_v_frame(payload) except: logger.warning("Cannot extract v-frame. Drop pkt!") return vf_index = vfs_model.compute_vf_index(len(v_frame), NODE_ID, seed) alloc_index, in_rand_frame = vfs_model.compute_alloc_index( vf_index, NODE_ID, v_frame, node_amount) stop_rx_ts = now_timestamp + 0.4 # TODO: Duo to various delays, adjust a bit to before firing round up second next_tx_ts = begin_timestamp + (NODE_SLOT_TIME * alloc_index) - TRANSMIT_DELAY logger.info( "{} Node recv VFS_BROADCAST {}, BS time {}, Total {}, Seed {}, Delay {}, " "\nv-frame index: {}, alloc-index: {}, fall to rand-frame: {}," "\nv-frame: {}".format( str(datetime.fromtimestamp(now_timestamp)), pktno, str(datetime.fromtimestamp(pkt_timestamp)), node_amount, seed, delta, vf_index, alloc_index, in_rand_frame, v_frame)) # logger.debug("begin {}, stop_rx_ts {}, next_tx_ts {}".format( # str(datetime.fromtimestamp(begin_timestamp)), str(datetime.fromtimestamp(stop_rx_ts)), # str(datetime.fromtimestamp(next_tx_ts)))) return def fire_at_absolute_second(): for i in range(10000): check_time = tx_tb.sink.get_time_now().get_real_secs() pivot_time = math.ceil(check_time) variance = pivot_time - check_time if -0.0002 < variance < 0.0002: logger.info("Fire at absolute {}".format( str(datetime.fromtimestamp(check_time)))) break time.sleep(0.0001) def usrp_sleep(interval_sec): wake_up_timestamp = tx_tb.sink.get_time_now().get_real_secs( ) + interval_sec for i in range(50000): now_timestamp = tx_tb.sink.get_time_now().get_real_secs() if now_timestamp >= wake_up_timestamp: break time.sleep(0.0001) def fire_at_expected_time(start_time): for i in range(50000): now_timestamp = tx_tb.sink.get_time_now().get_real_secs() if now_timestamp >= start_time: logger.info("Fire at {}".format( str(datetime.fromtimestamp(now_timestamp)))) return time.sleep(0.0001) logger.warning("ALERT!! not fire at {}".format( str(datetime.fromtimestamp(start_time)))) def check_thread_is_done(max_pkt_amt): for i in range(10000): if not my_thread.is_alive() and my_iteration >= max_pkt_amt: now_ts = tx_tb.sink.get_time_now().get_real_secs() logger.debug("{} - thread done - ".format( str(datetime.fromtimestamp(now_ts)))) return time.sleep(0.0001) now_ts = tx_tb.sink.get_time_now().get_real_secs() logger.debug("ALERT!! thread timeout at {}".format( str(datetime.fromtimestamp(now_ts)))) ####################################### # main ####################################### parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-s", "--size", type="eng_float", default=400, help="set packet size [default=%default]") parser.add_option("-M", "--megabytes", type="eng_float", default=1.0, help="set megabytes to transmit [default=%default]") parser.add_option("", "--discontinuous", action="store_true", default=False, help="enable discontinuous mode") parser.add_option("", "--from-file", default=None, help="use intput file for packet contents") parser.add_option("", "--to-file", default=None, help="Output file for modulated samples") # Add unused log_file option to prevent 'no such option' error parser.add_option("", "--logfile", default=None) parser.add_option("", "--scheme", default=None) digital.ofdm_mod.add_options(parser, expert_grp) digital.ofdm_demod.add_options(parser, expert_grp) transmit_path.add_options(parser, expert_grp) receive_path.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) uhd_receiver.add_options(parser) (options, args) = parser.parse_args() if len(args) != 0: logger.error("Parse error: {}\n".format(sys.stderr)) sys.exit(1) logger.info("----------------------------------------------------------") logger.info("Input options: \n{}".format(str(options))) logger.info("----------------------------------------------------------\n") if options.rx_freq is None or options.tx_freq is None: logger.error("You must specify -f FREQ or --freq FREQ\n") sys.exit(1) if options.scheme is None: logger.error("You must specify --scheme SCHEME\n") sys.exit(1) options.scheme = options.scheme.upper() if options.scheme not in [str(e) for e in list(Scheme)]: logger.error("Not support scheme: {}\n".format(options.scheme)) sys.exit(1) # Decide is BS or Node role IS_BS_ROLE = not bool(options.args) # build tx/rx tables tx_tb = TxTopBlock(options) if IS_BS_ROLE: rx_tb = RxTopBlock(rx_bs_callback, options) else: # Node role rx_tb = RxTopBlock(rx_node_callback, options) # Use device serial number as Node ID NODE_ID = tx_tb.sink.get_usrp_mboard_serial() # Append to required length NODE_ID = NODE_ID.zfill(NODE_ID_LEN) assert len( NODE_ID) == NODE_ID_LEN, "USRP NODE_ID {} len must be {}".format( NODE_ID, NODE_ID_LEN) logger.info("\nNODE ID: {}".format(NODE_ID)) logger.info("\nClock Rate: {} MHz".format(tx_tb.sink.get_clock_rate() / 1000000)) logger.info("\n####### Test Protocol: {} #######".format(options.scheme)) if IS_BS_ROLE: logger.info("\nPresume known nodes: {}".format(TEST_NODE_LIST)) # USRP device aligns with PC time (NTP) pc_now = time.time() tx_tb.sink.set_time_now(uhd.time_spec(pc_now)) now_ts = tx_tb.sink.get_time_now().get_real_secs() logger.info("\n{} Adjust to PC time: {}\n".format( str(datetime.fromtimestamp(time.time())), str(datetime.fromtimestamp(now_ts)))) # now_ts2 = rx_tb.source.get_time_now().get_real_secs() # sys_time = uhd.time_spec.get_system_time().get_real_secs() # logger.debug("\n{} Time alignment... Device txtime: {}, rxtime: {}, system time: {}\n".format( # str(datetime.fromtimestamp(time.time())), str(datetime.fromtimestamp(get_time)), # str(datetime.fromtimestamp(now_ts2)), str(datetime.fromtimestamp(sys_time)))) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: logger.error("Warning: failed to enable realtime scheduling") pkt_size = int(options.size) tx_tb.start() rx_tb.start() for y in range(REPEAT_TEST_COUNT): logger.info( "\n\n=============================================================================================" ) logger.info( "========================================== ROUND {} ==========================================" .format(y + 1)) logger.info( "=============================================================================================\n\n" ) ##################### SYNC : START ##################### if IS_BS_ROLE: ################# BS ################# _sync_start = tx_tb.sink.get_time_now().get_real_secs() sync_counts = 2 for z in range(sync_counts): # Note: TX cannot be lock initially if z == 0 and y == 0: rx_tb.lock() else: tx_tb.unlock() logger.info("------ Broadcast Beacon ------") _start = tx_tb.sink.get_time_now().get_real_secs() # BS: Send beacon signals. Time precision thread do_every_beacon(0.005, send_beacon_pkt, tx_tb, pkt_size, MAX_PKT_AMT) # Clocking thread check_thread_is_done(MAX_PKT_AMT) _end = rx_tb.source.get_time_now().get_real_secs() logger.info(" - duration {} -".format(_end - _start)) logger.info("------ Broadcast Beacon end --------") tx_tb.lock() # sleep longer in last loop, finishing sync cycle sleep_sec = 0.5 if z == sync_counts - 1 else 0.2 logger.info("Sleep for {} second\n".format(sleep_sec)) usrp_sleep(sleep_sec) logger.info(" - Sync duration {} -\n".format( rx_tb.source.get_time_now().get_real_secs() - _sync_start)) # # Deprecated. PROF TSENG: No need response-beacon, might cause collision # rx_tb.unlock() # logger.info("------ Listening ------") # next_tx_ts = 0 # reset next_tx # while next_tx_ts == 0 or next_tx_ts > now_ts: # time.sleep(0.01) # now_ts = rx_tb.source.get_time_now().get_real_secs() # # logger.debug("now {} next {}".format(str(datetime.fromtimestamp(now_ts)), str(datetime.fromtimestamp(next_tx_ts)))) # logger.info("------ Stop listen at {} ------".format(str(datetime.fromtimestamp(now_ts)))) # rx_tb.lock() ################ BS end ############## else: ################ Node ################ # Note: TX cannot be lock initially if y != 0: rx_tb.unlock() logger.info("------ Listening ------") stop_rx_ts = 0 # reset while stop_rx_ts == 0 or stop_rx_ts > now_ts: time.sleep(0.01) now_ts = rx_tb.source.get_time_now().get_real_secs() # logger.debug("now {} next {}".format(str(datetime.fromtimestamp(now_ts)), str(datetime.fromtimestamp(stop_rx_ts)))) rx_tb.lock() logger.info("------ Stop listen at {} ------".format( str(datetime.fromtimestamp(now_ts)))) # Deprecated. PROF TSENG: No need response-beacon, might cause collision # for z in range(2): # # if z != 0: # rx_tb.unlock() # logger.info("------ Listening ------") # next_tx_ts = 0 # reset next_tx # while next_tx_ts == 0 or next_tx_ts > now_ts: # time.sleep(0.01) # now_ts = rx_tb.source.get_time_now().get_real_secs() # # logger.debug("now {} next {}".format(str(datetime.fromtimestamp(now_ts)), str(datetime.fromtimestamp(next_tx_ts)))) # logger.info("------ Stop listen at {} ------".format(str(datetime.fromtimestamp(now_ts)))) # rx_tb.lock() # # if z != 0: # tx_tb.unlock() # logger.info("------ Send Response Beacon ------") # _start = tx_tb.sink.get_time_now().get_real_secs() # # Node: Send response-beacon signals. Time precision thread # do_every_beacon(0.005, send_resp_beacon_pkt, tx_tb, pkt_size, MAX_PKT_AMT) # # Clocking thread # check_thread_is_done(MAX_PKT_AMT) # _end = rx_tb.source.get_time_now().get_real_secs() # logger.info(" - duration {} -".format(_end - _start)) # logger.info("------ Send Response Beacon end ------") # tx_tb.lock() ################ Node end ############ ######################## SYNC : END ######################### if options.scheme == Scheme.PS.key: ################### Perfect Scheme: START ################### if IS_BS_ROLE: ################# BS ################# # Deprecated # nodes_sync_delta.update({NODE_ID_A: [1, 2, 3], # NODE_ID_B: [4, 5, 6], # '0000000003': [7, 8, 9], # '0000000004': [10, 11, 12], # '0000000005': [13, 14, 15]}) # node_amount = len(nodes_sync_delta) # rx_tb.lock() # Mark Frame T start time _ps_start = tx_tb.sink.get_time_now().get_real_secs() # calculate perfect seed _start = tx_tb.sink.get_time_now().get_real_secs() ps_model.generate_perfect_seed(TEST_NODE_LIST) _end = rx_tb.source.get_time_now().get_real_secs() logger.info(" - duration {} -".format(_end - _start)) tx_tb.unlock() logger.info("------ Broadcast PS packets ------") # To ensure broadcast end within a full second, adjust to start at absolute second fire_at_absolute_second() _start = tx_tb.sink.get_time_now().get_real_secs() do_every_protocol_bs(0.005, ps_model.broadcast_ps_pkt, tx_tb, pkt_size, len(TEST_NODE_LIST), MAX_PKT_AMT) # Clocking thread check_thread_is_done(MAX_PKT_AMT) _end = rx_tb.source.get_time_now().get_real_secs() logger.info(" - duration {} -".format(_end - _start)) logger.info("------ Broadcast PS end ------") tx_tb.lock() rx_tb.unlock() logger.info("------ Listen PS packets start ------") listen_only_to = [PacketType.PS_PKT.index] _start = tx_tb.sink.get_time_now().get_real_secs() # Listen end time is after last node transmission ended. Add some misc delay stop_rx_ts = ps_model.nodes_expect_time[-1][-1] + 0.5 while stop_rx_ts == 0 or stop_rx_ts > now_ts: time.sleep(0.01) now_ts = rx_tb.source.get_time_now().get_real_secs() # logger.debug("now {} next {}".format(str(datetime.fromtimestamp(now_ts)), str(datetime.fromtimestamp(next_tx_ts)))) _end = rx_tb.source.get_time_now().get_real_secs() logger.info(" - duration {} -".format(_end - _start)) logger.info("------ Listen PS packets end ------") listen_only_to = [] rx_tb.lock() now_ts = rx_tb.source.get_time_now().get_real_secs() logger.info("\n - PS duration {} -".format(now_ts - _ps_start)) logger.info("------ PS cycle ends at {} ------\n".format( str(datetime.fromtimestamp(now_ts)))) # logger.info("Sleep for 0.2 second") # usrp_sleep(0.2) ################ BS end ############## else: ################ Node ################ rx_tb.unlock() logger.info("------ Listening PS broadcast ------") listen_only_to = [PacketType.PS_BROADCAST.index] stop_rx_ts = 0 # reset while stop_rx_ts == 0 or stop_rx_ts > now_ts: time.sleep(0.01) now_ts = rx_tb.source.get_time_now().get_real_secs() # logger.debug("now {} next {}".format(str(datetime.fromtimestamp(now_ts)), str(datetime.fromtimestamp(stop_rx_ts)))) logger.info( "------ Stop listen PS broadcast at {} ------".format( str(datetime.fromtimestamp(now_ts)))) listen_only_to = [] rx_tb.lock() # TODO: Adjust to node alloc period assert alloc_index != -1, "alloc_index is -1" logger.info("------ Ready to send PS packets ------") if y != 0: tx_tb.unlock() fire_at_expected_time(next_tx_ts + COMMAND_DELAY) _start = tx_tb.sink.get_time_now().get_real_secs() ps_data = "Hello, I am node {}".format(NODE_ID) do_every_protocol_node(0.005, ps_model.send_ps_pkt, NODE_ID, tx_tb, pkt_size, ps_data, MAX_PKT_AMT_FOR_NODE) # Clocking thread check_thread_is_done(MAX_PKT_AMT_FOR_NODE) _end = rx_tb.source.get_time_now().get_real_secs() logger.info(" - duration {} -".format(_end - _start)) logger.info("------ Send PS packets end ------") tx_tb.lock() # Node wait until PS cycle is over now_ts = rx_tb.source.get_time_now().get_real_secs() usrp_sleep(ps_end_ts - now_ts + COMMAND_DELAY) now_ts = rx_tb.source.get_time_now().get_real_secs() logger.info("\n------ PS cycle ends at {} ------\n".format( str(datetime.fromtimestamp(now_ts)))) ################ Node end ############ ##################### Perfect Scheme: END ##################### elif options.scheme == Scheme.VFS.key: ################### Virtual Frame Scheme: START ################### if IS_BS_ROLE: ################# BS ################# # Deprecated # nodes_sync_delta.update({NODE_ID_A: [1, 2, 3], # NODE_ID_B: [4, 5, 6], # '0000000003': [7, 8, 9], # '0000000004': [10, 11, 12], # '0000000005': [13, 14, 15]}) # node_amount = len(nodes_sync_delta) # rx_tb.lock() # Mark Frame T start time & expected end time vfs_start_ts = tx_tb.sink.get_time_now().get_real_secs() vfs_end_ts = vfs_start_ts + FRAME_TIME_T - 0.01 # give a bit deplay for ending # calculate VFS seed, v-frame & rand-frame _start = tx_tb.sink.get_time_now().get_real_secs() vfs_model.generate_seed_v_frame_rand_frame(TEST_NODE_LIST) _end = rx_tb.source.get_time_now().get_real_secs() logger.info(" - duration {} -".format(_end - _start)) tx_tb.unlock() logger.info("------ Broadcast VFS packets ------") # To ensure broadcast end within a full second, adjust to start at absolute second fire_at_absolute_second() _start = tx_tb.sink.get_time_now().get_real_secs() do_every_protocol_bs(0.005, vfs_model.broadcast_vfs_pkt, tx_tb, pkt_size, len(TEST_NODE_LIST), MAX_PKT_AMT) # Clocking thread check_thread_is_done(MAX_PKT_AMT) _end = rx_tb.source.get_time_now().get_real_secs() logger.info(" - duration {} -".format(_end - _start)) logger.info("------ Broadcast VFS end ------") tx_tb.lock() rx_tb.unlock() logger.info("------ Listen VFS packets start ------") listen_only_to = [PacketType.VFS_PKT.index] _start = tx_tb.sink.get_time_now().get_real_secs() # Listen end time is after last node transmission ended, or till frame T ended. stop_rx_ts = vfs_model.nodes_expect_time[-1][ -1] + 0.5 # Add misc delay while stop_rx_ts == 0 or stop_rx_ts > now_ts or vfs_end_ts > now_ts: time.sleep(0.01) now_ts = rx_tb.source.get_time_now().get_real_secs() # logger.debug("now {} next {}".format(str(datetime.fromtimestamp(now_ts)), str(datetime.fromtimestamp(next_tx_ts)))) _end = rx_tb.source.get_time_now().get_real_secs() logger.info(" - duration {} -".format(_end - _start)) logger.info("------ Listen VFS packets end ------") listen_only_to = [] rx_tb.lock() now_ts = rx_tb.source.get_time_now().get_real_secs() logger.info("\n - VFS duration {} -".format(now_ts - vfs_start_ts)) logger.info("------ VFS cycle ends at {} ------\n".format( str(datetime.fromtimestamp(now_ts)))) # logger.info("Sleep for 0.2 second") # usrp_sleep(0.2) ################# BS end ############# else: ################ Node ################ # Mark Frame T start time & expected end time vfs_start_ts = tx_tb.sink.get_time_now().get_real_secs() vfs_end_ts = vfs_start_ts + FRAME_TIME_T - 0.01 # give a bit deplay for ending rx_tb.unlock() logger.info("------ Listening VFS broadcast ------") listen_only_to = [PacketType.VFS_BROADCAST.index] stop_rx_ts = 0 # reset while stop_rx_ts == 0 or stop_rx_ts > now_ts: time.sleep(0.01) now_ts = rx_tb.source.get_time_now().get_real_secs() # logger.debug("now {} next {}".format(str(datetime.fromtimestamp(now_ts)), str(datetime.fromtimestamp(stop_rx_ts)))) logger.info( "------ Stop listen VFS broadcast at {} ------".format( str(datetime.fromtimestamp(now_ts)))) listen_only_to = [] rx_tb.lock() # TODO: Adjust to node alloc period if alloc_index == -1: logger.warning( "WARNING: alloc_index is -1, cannot join this session. Skip..." ) time.sleep(7) continue # assert alloc_index != -1, "alloc_index is -1" logger.info("------ Ready to send VFS packets ------") if y != 0: tx_tb.unlock() fire_at_expected_time(next_tx_ts + COMMAND_DELAY) _start = tx_tb.sink.get_time_now().get_real_secs() vfs_data = "Hello, I am node {}".format(NODE_ID) do_every_protocol_node(0.005, vfs_model.send_vfs_pkt, NODE_ID, tx_tb, pkt_size, vfs_data, MAX_PKT_AMT_FOR_NODE) # Clocking thread check_thread_is_done(MAX_PKT_AMT_FOR_NODE) _end = rx_tb.source.get_time_now().get_real_secs() logger.info(" - duration {} -".format(_end - _start)) logger.info("------ Send VFS packets end ------") tx_tb.lock() # Node wait until VFS cycle is over now_ts = rx_tb.source.get_time_now().get_real_secs() usrp_sleep(vfs_end_ts - now_ts + COMMAND_DELAY) now_ts = rx_tb.source.get_time_now().get_real_secs() logger.info("\n - VFS duration {} -".format(now_ts - vfs_start_ts)) logger.info("------ VFS cycle ends at {} ------\n".format( str(datetime.fromtimestamp(now_ts)))) ################ Node end ############ ##################### Virtual Frame Scheme: END ##################### #tx_tb.unlock() #tx_tb.wait() #rx_tb.unlock() #rx_tb.wait() tx_tb.stop() rx_tb.stop() logger.info( "\n\n=============================================================================================" ) logger.info( "========================================= TEST END ==========================================" ) logger.info( "=============================================================================================\n\n" ) sys.exit(0)
def main(): def send_pkt(which, payload="", eof=False): return tb.txpath[which].send_pkt(payload, eof) mods = digital.modulation_utils.type_1_mods() parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option( "-m", "--modulation", type="choice", choices=mods.keys(), default="qam", help="Select modulation from: %s [default=%%default]" % (", ".join(mods.keys()),), ) parser.add_option("-s", "--size", type="eng_float", default=1500, help="set packet size [default=%default]") parser.add_option( "-M", "--megabytes", type="eng_float", default=1.0, help="set megabytes to transmit [default=%default]" ) parser.add_option( "", "--discontinuous", action="store_true", default=False, help="enable discontinous transmission (bursts of 5 packets)", ) parser.add_option("", "--from-file", default=None, help="use intput file for packet contents") parser.add_option("", "--to-file", default=None, help="Output file for modulated samples") custom_grp = parser.add_option_group("Custom") custom_grp.add_option( "", "--band-trans-width", type="eng_float", default=75e3, help="transition width for band pass filter" ) custom_grp.add_option( "", "--low-trans-width", type="eng_float", default=75e3, help="transition width for low pass filter" ) custom_grp.add_option("", "--guard-width", type="eng_float", default=100e3, help="guard region width") custom_grp.add_option("", "--file-samp-rate", type="eng_float", default=1e6, help="file sample rate") custom_grp.add_option("", "--split-amplitude", type="eng_float", default=0.15, help="multiplier post split") custom_grp.add_option("", "--rs-n", type="int", default=194, help="reed solomon n") custom_grp.add_option("", "--rs-k", type="int", default=188, help="reed solomon k") custom_grp.add_option("", "--num-taps", type="int", default=2, help="reed solomon k") transmit_path.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) for mod in mods.values(): mod.add_options(expert_grp) (options, args) = parser.parse_args() options.bitrate = 3000e3 options.tx_gain = 25 options.constellation_points = 16 if len(args) != 0: parser.print_help() sys.exit(1) if options.from_file is not None: source_file = open(options.from_file, "r") # build the graph tb = my_top_block(mods[options.modulation], options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() # start flow graph # generate and send packets nbytes = int(1e6 * options.megabytes) n = 0 pktno = 0 pkt_size = int(options.size) while n < nbytes: for i in range(2): if options.from_file is None: data = (pkt_size - 2) * chr(pktno & 0xFF) else: data = source_file.read(pkt_size - 2) if data == "": break payload = struct.pack("!H", pktno & 0xFFFF) + data send_pkt(i, payload) n += len(payload) sys.stderr.write(".") if options.discontinuous and pktno % 5 == 4: time.sleep(1) pktno += 1 send_pkt(0, eof=True) send_pkt(1, eof=True) tb.wait() # wait for it to finish
def main(): random.seed(os.urandom(100)) def send_pkt(payload='', eof=False): return tb.txpath.send_pkt(payload, eof) mods = digital.modulation_utils.type_1_mods() parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='gmsk', help="Select modulation from: %s [default=%%default]" % (', '.join(mods.keys()),)) parser.add_option("-s", "--size", type="eng_float", default=1500, help="set packet size [default=%default]") parser.add_option("-M", "--megabytes", type="eng_float", default=1.0, help="set megabytes to transmit [default=%default]") parser.add_option("","--discontinuous", action="store_true", default=False, help="enable discontinous transmission (bursts of 5 packets)") parser.add_option("","--from-file", default=None, help="use intput file for packet contents") parser.add_option("","--to-file", default=None, help="Output file for modulated samples") parser.add_option("-E", "--exp-id", type="string", default="test", help="specify the experiment ID") parser.add_option("-N", "--node-id", type="string", default="tx", help="specify the experiment ID") parser.add_option("","--server", action="store_true", default=False, help="To take data from the server") parser.add_option("", "--port", type="int", default=None, help="specify the server port") transmit_path.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) for mod in mods.values(): mod.add_options(expert_grp) (options, args) = parser.parse_args () omlDb = OMLBase("gnuradiorx",options.exp_id,options.node_id,"tcp:nitlab3.inf.uth.gr:3003") omlDb.addmp("packets", "type:string value:long") omlDb.start() if len(args) != 0: parser.print_help() sys.exit(1) if options.from_file is not None: source_file = open(options.from_file, 'r') # build the graph tb = my_top_block(mods[options.modulation], options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() # start flow graph # generate and send packets nbytes = int(1e6 * options.megabytes) n = 0 pktno = 0 pkt_size = int(options.size) # connect to server if options.server: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # server_address = ('10.0.1.200', 51000) server_address = ('10.0.1.200', options.port) print >>sys.stderr, 'connecting to %s port %s' % server_address sock.connect(server_address) freq_list = [options.tx_freq, options.tx_freq+1000000.0, options.tx_freq-1000000.0] payload_buffer = [] curr_freq = best_freq= options.tx_freq while pktno<1000: if options.server: data = ""; while len(data) < pkt_size: if (pktno<1000): data += sock.recv(pkt_size - len(data)) if data == '': # No more data received from server sock.close() break; elif options.from_file is None: data = (pkt_size - 2) * chr(pktno & 0xff) else: data = source_file.read(pkt_size - 2) if data == '': break; if pktno%200==0: time.sleep(0.7) tb.source.set_center_freq(uhd.tune_request(curr_freq,0)) time.sleep(0.01) if(tb.probe.level()>0.15): #find best freq lowest=3 i=0 for i in range (len(freq_list)): #if freq_list[i]!=curr_freq: tb.source.set_center_freq(uhd.tune_request(freq_list[i],0)) time.sleep(0.01) measurement = tb.probe.level() if measurement<lowest: lowest = measurement best_freq = freq_list[i] curr_freq = best_freq tb.sink.set_freq(best_freq,0) payload = struct.pack('!H', pktno & 0xffff) + data send_pkt(payload) payload_buffer.insert(pktno,payload) n += len(payload) sys.stderr.write('.') omlDb.inject("packets", ("sent", pktno)) if options.discontinuous and pktno % 5 == 4: time.sleep(1) pktno += 1 i=0 while(1): if i==40 :#problematic packets for k in range(0,5): send_pkt(payload_buffer[k*200+199]) send_pkt(payload_buffer[k*200]) if i%200==0: time.sleep(0.7) tb.source.set_center_freq(uhd.tune_request(curr_freq,0)) time.sleep(0.01) if(tb.probe.level()>0.15): #find best freq lowest=3 for j in range (len(freq_list)): #if freq_list[j]!=curr_freq: tb.source.set_center_freq(uhd.tune_request(freq_list[j],0)) time.sleep(0.01) measurement = tb.probe.level() if measurement<lowest: lowest = measurement best_freq = freq_list[j] curr_freq = best_freq tb.sink.set_freq(best_freq,0) send_pkt(payload_buffer[i%1000]) i+=1 send_pkt(eof=True) tb.wait() # wait for it to finish