def add_options(normal, expert): """ Adds usrp-specific options to the Options Parser """ 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) 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]") normal.add_option("-R", "--rx-subdev-spec", type="subdev", default=None, help="select USRP Rx side A or B") normal.add_option("", "--rx-gain", type="eng_float", default=None, metavar="GAIN", help="set receiver gain in dB [default=midpoint]. See also --show-rx-gain-range") normal.add_option("", "--show-rx-gain-range", action="store_true", default=False, help="print min and max Rx gain available on selected daughterboard") normal.add_option("-v", "--verbose", action="store_true", default=False) expert.add_option("", "--rx-freq", type="eng_float", default=None, help="set Rx frequency to FREQ [default=%default]", metavar="FREQ") expert.add_option("-d", "--decim", type="intx", default=128, help="set fpga decimation rate to DECIM [default=%default]") expert.add_option("", "--snr", type="eng_float", default=30, help="set the SNR of the channel in dB [default=%default]") #other necessary options transmit_path.add_options(normal, expert) receive_path.add_options(normal, expert) blks2.ofdm_mod.add_options(normal, expert) blks2.ofdm_demod.add_options(normal, expert) fusb_options.add_options(expert)
def __init__(self, midFreq, fft_len, occupied_len, cp_len, inter): if midFreq == None or fft_len == None or \ occupied_len == None or cp_len == None: print 'param is not ok!' return args = ['--tx-amplitude', '5000', '-i', str(inter), '-T', 'B', '-v'] args.append('-f') args.append(str(midFreq)) args.append('--fft-length') args.append(str(fft_len)) args.append('--occupied-tones') args.append(str(occupied_len)) args.append('--cp-length') args.append(str(cp_len)) parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") my_top_block.add_options(parser, expert_grp) transmit_path.add_options(parser, expert_grp) blks2.ofdm_mod.add_options(parser, expert_grp) blks2.ofdm_demod.add_options(parser, expert_grp) fusb_options.add_options(expert_grp) (options, args) = parser.parse_args(args) self.tb = my_top_block(options) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print 'Warning: failed to enable realtime scheduling' self.tb.start() print 'tx init ok!'
def add_options(normal, expert): """ Adds usrp-specific options to the Options Parser """ common_tx_rx_usrp_options(normal,expert) transmit_path.add_options(normal,expert) normal.add_option("-T", "--tx-subdev-spec", type="subdev", default=None, help="select USRP Tx side A or B") expert.add_option("", "--tx-freq", type="eng_float", default=None, help="set transmit frequency to FREQ [default=%default]", metavar="FREQ") normal.add_option("", "--measure", action="store_true", default=False, help="enable troughput measure, usrp disabled"); normal.add_option("", "--dyn-freq", action="store_true", default=False, help="enable troughput measure, usrp disabled"); expert.add_option("", "--snr", type="eng_float", default=None, help="Simulate AWGN channel"); expert.add_option("", "--freqoff", type="eng_float", default=None, help="Simulate frequency offset [default=%default]") expert.add_option("", "--samplingoffset", type="eng_float", default=None, help="Simulate sampling frequency offset [default=%default]") expert.add_option("", "--berm", action="store_true", default=False, help="Enable static AWGN power for BER measurement") expert.add_option("", "--online-work", action="store_true", default=False, help="Force the ofdm transmitter to work during file record [default=%default]") normal.add_option("", "--from-file", type="string", default=None, help="Sent recorded stream with usrp") normal.add_option("", "--to-file", type="string", default=None, help="Record transmitter to disk, not being sent to usrp") expert.add_option("", "--force-filter", action="store_true", default=False, help="force filter use while transmitting to file or measuring") expert.add_option("", "--nullsink", action="store_true", default=False, help="Throw away samples") normal.add_option("-e", "--interface", type="string", default="eth0", help="select Ethernet interface, default is eth0") normal.add_option("-m", "--mac-addr", type="string", default="", help="select USRP by MAC address, default is auto-select") normal.add_option("", "--usrp2", action="store_true", default=False, help="Use USRP2 Interface") expert.add_option("", "--record", action="store_true", default=False, help="Record transmission stream") expert.add_option("", "--stations", type="intx", default=1, help="Mobile station count") normal.add_option("", "--coding", action="store_true", default=False, help="Enable channel coding") expert.add_option("", "--est-preamble", type="int", default=1, help="the number of channel estimation preambles (1 or 2)")
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(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(): 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 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 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) * 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 send_pkt(eof=True) tb.wait() # wait for it to finish
def main(): global file 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("", "--from-file", default=None, help="Use input file for packet contents") parser.add_option("", "--samples-file", default=None, help="Output file for modulated samples") transmit_path.add_options(parser, 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") tb = loop_top_block(mods[options.modulation], options) # do we need to do this for our test bench? r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" tb.start() pkt_size = int(options.size) while True: data = source_file.read(pkt_size) if data == "": break # payload = struct.pack('!H', pktno & 0xffff) + data payload = data send_pkt(payload)
def main(): parser = OptionParser(conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") ofdm_mrrc_benchmark.add_options(parser, expert_grp) transmit_path.add_options(parser, expert_grp) receive_path.add_options(parser, expert_grp) fusb_options.add_options(expert_grp) parser.add_option("-c", "--cfg", action="store", type="string", default=None, help="Specifiy configuration file, default: none", config="false") (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) benchmark = ofdm_mrrc_benchmark(options) runtime = benchmark r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Couldn't enable realtime scheduling" else: print "Enabled realtime scheduling" try: if options.dot_graph: string_benchmark = runtime.dot_graph() filetx = os.path.expanduser('benchmark_mrrc_ofdm.dot') dot_file = open(filetx, 'w') dot_file.write(string_benchmark) dot_file.close() runtime.run() #runtime.start() try: tx.txpath._control._id_source.ready() except: pass except KeyboardInterrupt: runtime.stop() runtime.wait() if options.measure: print "min", tx.m.get_min() print "max", tx.m.get_max() print "avg", tx.m.get_avg()
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(): parser = OptionParser(conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") ofdm_mrrc_benchmark.add_options(parser, expert_grp) transmit_path.add_options(parser, expert_grp) receive_path.add_options(parser, expert_grp) fusb_options.add_options(expert_grp) parser.add_option( "-c", "--cfg", action="store", type="string", default=None, help="Specifiy configuration file, default: none", config="false" ) (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 ) benchmark = ofdm_mrrc_benchmark(options) runtime = benchmark r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Couldn't enable realtime scheduling" else: print "Enabled realtime scheduling" try: if options.dot_graph: string_benchmark = runtime.dot_graph() filetx = os.path.expanduser('benchmark_mrrc_ofdm.dot') dot_file = open(filetx,'w') dot_file.write(string_benchmark) dot_file.close() runtime.run() #runtime.start() try: tx.txpath._control._id_source.ready() except: pass except KeyboardInterrupt: runtime.stop() runtime.wait() if options.measure: print "min",tx.m.get_min() print "max",tx.m.get_max() print "avg",tx.m.get_avg()
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") my_top_block.add_options(parser, expert_grp) transmit_path.add_options(parser, expert_grp) blks2.ofdm_mod.add_options(parser, expert_grp) blks2.ofdm_demod.add_options(parser, expert_grp) fusb_options.add_options(expert_grp) (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: send_pkt(struct.pack('!H', pktno) + (pkt_size - 2) * chr(pktno & 0xff)) n += pkt_size sys.stderr.write('.') if options.discontinuous and pktno % 5 == 1: time.sleep(1) pktno += 1 send_pkt(eof=True) tb.wait() # wait for it to finish
def main(): parser = OptionParser(conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") ofdm_tx.add_options(parser, expert_grp) transmit_path.add_options(parser, expert_grp) fusb_options.add_options(expert_grp) parser.add_option("-c", "--cfg", action="store", type="string", default=None, help="Specifiy configuration file, default: none", config="false") (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) tx = ofdm_tx(options) runtime = tx r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Couldn't enable realtime scheduling" else: print "Enabled realtime scheduling" try: orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID) string_tx = runtime.dot_graph() dot_file = open("text_tx.dot", 'w') dot_file.write(string_tx) dot_file.close() runtime.start() try: tx.txpath._control._id_source.ready() except: pass orb.run() except KeyboardInterrupt: runtime.stop() runtime.wait() if options.measure: print "min", tx.m.get_min() print "max", tx.m.get_max() print "avg", tx.m.get_avg()
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("", "--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") parser.add_option("", "--freq", type="int", dest="tx_freq", default=500000000, help="set tx freq") 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 n = 0 pktno = 0 c = 0 while True: data = raw_input() payload = data send_pkt(payload) send_pkt(eof=True) time.sleep(2) # allow time for queued packets to be sent tb.wait() # wait for it to finish
def main(): parser = OptionParser(conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") ofdm_tx.add_options(parser, expert_grp) transmit_path.add_options(parser, expert_grp) fusb_options.add_options(expert_grp) parser.add_option( "-c", "--cfg", action="store", type="string", default=None, help="Specifiy configuration file, default: none", config="false" ) (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 ) tx = ofdm_tx(options) runtime = tx r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Couldn't enable realtime scheduling" else: print "Enabled realtime scheduling" try: orb = CORBA.ORB_init(sys.argv,CORBA.ORB_ID) string_tx = runtime.dot_graph() dot_file = open("text_tx.dot",'w') dot_file.write(string_tx) dot_file.close() runtime.start() try: tx.txpath._control._id_source.ready() except: pass orb.run() except KeyboardInterrupt: runtime.stop() runtime.wait() if options.measure: print "min",tx.m.get_min() print "max",tx.m.get_max() print "avg",tx.m.get_avg()
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("","--gain", type="eng_float", default=11.5, help="set transmitter gain [default=%default]") my_top_block.add_options(parser, expert_grp) transmit_path.add_options(parser, expert_grp) blks2.ofdm_mod.add_options(parser, expert_grp) blks2.ofdm_demod.add_options(parser, expert_grp) #fusb_options.add_options(expert_grp) (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: #pktno % 65535 to account for sending very large amounts of data send_pkt(struct.pack('!H', pktno % 65535) + (pkt_size - 2) * chr(pktno & 0xff)) n += pkt_size sys.stderr.write('.') if options.discontinuous and pktno % 5 == 1: time.sleep(1) pktno += 1 send_pkt(eof=True) tb.wait() # wait for it to finish
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(): 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 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) 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(): global pkts_rcvd global EOF_rcvd global num_acks ########################### #set up options ########################### 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) parser.add_option("-p","--packets", type="int", default = 3000, help="set number of packets to send [default=%default]") parser.add_option("", "--address", type="string", default = None, help="set the address of the node (addresses are a single char) [default=%default]") expert_grp.add_option("-c", "--carrier-threshold", type="eng_float", default=-20, help="set carrier detect threshold (dB) [default=%default]") parser.add_option("", "--pkt-gen-time", type="eng_float", default=.05, help="set the time between sending each packet (s) [default=%default]") parser.add_option("", "--pkt-padding", type="int", default=1000, help="pad packet with pkt-padding number of extra chars [default=%default]") parser.add_option("","--autoselect-freq", action="store_true", default=False) parser.add_option("", "--test-time", type="int", default=500, help="number of seconds to run the test for [default=%default]") usrp_graph.add_options(parser, expert_grp) transmit_path.add_options(parser, expert_grp) receive_path.add_options(parser, expert_grp) blks2.ofdm_mod.add_options(parser, expert_grp) blks2.ofdm_demod.add_options(parser, expert_grp) cs_mac.add_options(parser, expert_grp) sense_path.add_options(parser, expert_grp) (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) if options.address is None: sys.stderr.write("You must specify a node address\n") parser.print_help(sys.stderr) sys.exit(1) ########################### #set PHY and MAC ########################### # 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" pkts_sent = 0 # instantiate the MAC mac = cs_mac(options, rx_callback) # build the graph (PHY) tx_failures = [] tb = usrp_graph(mac.phy_rx_callback, options) mac.set_flow_graph(tb) # give the MAC a handle for the PHY mac.set_error_array(tx_failures) ########################### #manage packet generation and data gathering ########################### print print "address: %s" % (options.address) print 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" tb.start() # Start executing the flow graph (runs in separate threads) if options.autoselect_freq: new_freq = mac.find_best_freq() raw_input("Press Enter to begin transmitting") #n = 0 #while n < 50: # os.system("clear") # new_freq = mac.find_best_freq() # time.sleep(.3) # n += 1 #return mac.start() start_time = time.clock() while (pkts_sent < options.packets + 3):# or not EOF_rcvd): #if options.verbose: # print "give a new packet to the MAC" if pkts_sent > options.packets: mac.new_packet('x', "EOF") else: mac.new_packet('x', str(pkts_sent).zfill(3) + options.pkt_padding * "k") # run the tests pkts_sent += 1 #while not EOF_rcvd: # time.sleep(options.pkt_gen_time) #for some reason the timing was off, and I need a factor of two to get it #approximately to where it should be while time.clock() - start_time < 2*options.test_time: pass mac.stop() mac.wait() #do stuff with the measurement results print print time.strftime("%X") print "this node sent: ", pkts_sent, " packets" print "there were: ", len(tx_failures), " packets that were not successfully sent" #print "this node received: ", num_acks, " ACK packets" print "this node rcvd: ", len(set(pkts_rcvd)), " packets" print "there were: ", len(pkts_rcvd) - len(set(pkts_rcvd)), " spurious packet retransmissions" print "collisions: ", mac.collisions if options.pkt_padding != 0: print "the packets this node sent were of length: ", len(str(pkts_sent).zfill(3) + options.pkt_padding * "k") + 2 # + 2 for the address chars #for item in pkts_rcvd: # print "\t", item #print "succesfully sent the following packets" #for item in mac.sent_pkts: # print "\t", item tb.stop() tb.wait() # wait for it to finish
def main(): global n_rcvd, n_right, pktno n_rcvd = 0 n_right = 0 pktno = 0 def rx_callback(ok, payload): global n_rcvd, n_right, pktno (pktno,) = struct.unpack('!H', payload[0:2]) n_rcvd += 1 if ok: n_right += 1 if not options.gui: print "ok = %5s pktno = %4d n_rcvd = %4d n_right = %4d" % ( ok, pktno, n_rcvd, n_right) def send_pkt(payload='', eof=False): return tb.txpath.send_pkt(payload, eof) mods = modulation_utils.type_1_mods() demods = modulation_utils.type_1_demods() parser = OptionParser(option_class=eng_option, conflict_handler="resolve") expert_grp = parser.add_option_group("Expert") channel_grp = parser.add_option_group("Channel") parser.add_option("-m", "--modulation", type="choice", choices=mods.keys(), default='dbpsk', 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("-G", "--gui", action="store_true", default=False, help="Turn on the GUI [default=%default]") channel_grp.add_option("", "--sample-rate", type="eng_float", default=1e5, help="set speed of channel/simulation rate to RATE [default=%default]") channel_grp.add_option("", "--snr", type="eng_float", default=30, help="set the SNR of the channel in dB [default=%default]") channel_grp.add_option("", "--frequency-offset", type="eng_float", default=0, help="set frequency offset introduced by channel [default=%default]") channel_grp.add_option("", "--timing-offset", type="eng_float", default=1.0, help="set timing offset introduced by channel [default=%default]") channel_grp.add_option("", "--seed", action="store_true", default=False, help="use a random seed for AWGN noise [default=%default]") transmit_path.add_options(parser, expert_grp) receive_path.add_options(parser, expert_grp) 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.exit(1) r = gr.enable_realtime_scheduling() if r != gr.RT_OK: print "Warning: failed to enable realtime scheduling" # Create an instance of a hierarchical block tb = my_top_block(mods[options.modulation], demods[options.modulation], rx_callback, options) tb.start() packet_sender = th_send(send_pkt, options.megabytes, options.size) packet_sender.start() if(options.gui): tb.qapp.exec_() packet_sender.stop() else: # Process until done; hack in to the join to stop on an interrupt while(packet_sender.isAlive()): try: packet_sender.join(1) except KeyboardInterrupt: packet_sender.stop()
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.query_database() myPay.pause() time.sleep(0.001) detection = myPay.feature_detect 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) ''' 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(): 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(): 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( "", "--snr", type="eng_float", default=30, help="set the SNR of the channel in dB [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) # 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(verbose=True) # build the graph (PHY) tb = my_top_block(mac.phy_rx_callback, mac.fwd_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" 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(): 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(): global n_rcvd, n_right n_rcvd = 0 n_right = 0 def send_pkt(payload='', eof=False): return tb.txpath.send_pkt(payload, eof) 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) 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("-s", "--size", type="eng_float", default=387, 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("-r", "--sample-rate", type="eng_float", default=1e5, help="limit sample rate to RATE in throttle (%default)") parser.add_option("", "--snr", type="eng_float", default=30, help="set the SNR of the channel in dB [default=%default]") parser.add_option("", "--frequency-offset", type="eng_float", default=0, help="set frequency offset introduced by channel [default=%default]") parser.add_option("", "--clockrate-ratio", type="eng_float", default=1.0, help="set clock rate ratio (sample rate difference) between two systems [default=%default]") parser.add_option("","--discontinuous", type="int", default=0, help="enable discontinous transmission, burst of N packets [Default is continuous]") parser.add_option("","--channel-off", action="store_true", default=False, help="Turns AWGN, freq offset channel off") parser.add_option("","--multipath-on", action="store_true", default=False, help="enable multipath") transmit_path.add_options(parser, expert_grp) receive_path.add_options(parser, expert_grp) digital.ofdm_mod.add_options(parser, expert_grp) digital.ofdm_demod.add_options(parser, expert_grp) (options, args) = parser.parse_args () # 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) #nbytes = int(options.size)*2 #nbytes = 0 n = 0 pktno = 0 pkt_size = int(options.size) """ while n < nbytes: #r = ''.join([chr(random.randint(0,255)) for i in range(pkt_size-2)]) #pkt_contents = struct.pack('!H', pktno) + r pkt_contents = struct.pack('!H', pktno) + (pkt_size - 2) * chr(pktno & 0xff) send_pkt(pkt_contents) n += pkt_size #sys.stderr.write('.') #if options.discontinuous and pktno % 5 == 4: time.sleep(0.5) pktno += 1 """ pkt_contents = struct.pack('!H', pktno) + (pkt_size - 2) * chr(pktno & 0xff) send_pkt(pkt_contents) n += pkt_size time.sleep(0.5) pktno += 1 send_pkt(pkt_contents) n += pkt_size time.sleep(0.5) pktno += 1 send_pkt(pkt_contents) n += pkt_size time.sleep(0.5) pktno += 1 #sys.stderr.write('.') #if options.discontinuous and pktno % 5 == 4: 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") 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]") usrp_graph.add_options(parser, expert_grp) transmit_path.add_options(parser, expert_grp) receive_path.add_options(parser, expert_grp) blks2.ofdm_mod.add_options(parser, expert_grp) blks2.ofdm_demod.add_options(parser, expert_grp) fusb_options.add_options(expert_grp) (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" # If the user hasn't set the fusb_* parameters on the command line, # pick some values that will reduce latency. if options.fusb_block_size == 0 and options.fusb_nblocks == 0: if realtime: # be more aggressive options.fusb_block_size = gr.prefs().get_long('fusb', 'rt_block_size', 1024) options.fusb_nblocks = gr.prefs().get_long('fusb', 'rt_nblocks', 16) else: options.fusb_block_size = gr.prefs().get_long('fusb', 'block_size', 4096) options.fusb_nblocks = gr.prefs().get_long('fusb', 'nblocks', 16) #print "fusb_block_size =", options.fusb_block_size #print "fusb_nblocks =", options.fusb_nblocks # instantiate the MAC mac = cs_mac(tun_fd, verbose=True) # build the graph (PHY) tb = usrp_graph(mac.phy_rx_callback, options) 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(fg.txpath.bitrate()),) #print "samples/symbol: %3d" % (fg.txpath.samples_per_symbol(),) #print "interp: %3d" % (fg.txpath.interp(),) #print "decim: %3d" % (fg.rxpath.decim(),) 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, 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(): 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("", "--gain", type="eng_float", default=13, help="set transmitter gain [default=%default]") parser.add_option( "", "--channel-interval", type="eng_float", default=5, help="set the time between channel changes [default=%default]") #parser.add_option("","--num-channels", type="int", default=1, # help="set number of (contiguous) occupied channels [default=%default]") #parser.add_option("", "--start-freq", type="eng_float", default="631M", # help="set the start of the frequency band to sense over [default=%default]") #parser.add_option("", "--end-freq", type="eng_float", default="671M", # help="set the end of the frequency band to sense over [default=%default]") parser.add_option("", "--random", action="store_true", default=False, help="enable random frequency selection") parser.add_option( "", "--channel_rate", type="eng_float", default=6e6, help="Set bandwidth of an expected channel [default=%default]") my_top_block.add_options(parser, expert_grp) transmit_path.add_options(parser, expert_grp) blks2.ofdm_mod.add_options(parser, expert_grp) blks2.ofdm_demod.add_options(parser, expert_grp) #fusb_options.add_options(expert_grp) (options, args) = parser.parse_args() total_samp_rate = options.rate #*options.num_channels channels = [ 600000000, 620000000, 625000000, 640000000, 645000000, 650000000 ] # 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) #timing parameters last_change = time.clock() print "\nstarting frequency: ", options.tx_freq, " at time: ", time.strftime( "%X") current_chan = 0 while n < nbytes: if time.clock() - last_change < options.channel_interval: #pktno % 65535 to account for sending very large amounts of data send_pkt( struct.pack('!H', pktno % 65535) + (pkt_size - 2) * chr(pktno & 0xff)) n += pkt_size sys.stderr.write('.') if options.discontinuous and pktno % 5 == 1: time.sleep(1) pktno += 1 else: #change channels if options.random: current_chan = random.randint(0, len(channels) - 1) else: current_chan = (current_chan + 1) % len(channels) new_freq = channels[current_chan] #if options.num_channels == 1: # new_freq = (options.start_freq + 3*options.channel_rate/2) + (random.randint(0,4))*options.channel_rate #elif options.num_channels == 3: # new_freq = (options.start_freq + 3*options.channel_rate/2) + (random.randint(1,5))*options.rate #else: # pass #just do nothing for now last_change = time.clock() print "\nchanging frequencies to ", new_freq, " at time ", time.strftime( "%X") tb.set_freq(new_freq) 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(): #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, go_on_flag,file_input,\ file_output, data, data_num 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 go_on_flag = True alloc_index = -1 last_node_amount = -1 data = "**heLLo**" # default data str data_num = 0 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) logger.info( "Input file opened successfully") except: logger.error( "Error: file not exist") # 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, go_on_flag, data_num logger.info("Please start host now...") boot_time = time.time() bs_start_time = 0 nd_start_time = 0 nd_in_response = False time_data_collecting = len(TEST_NODE_LIST)*NODE_SLOT_TIME time_wait_for_my_slot = 0 while thread_run: if IS_BS: if time.time() > (bs_start_time + time_data_collecting+TRANSMIT_DELAY): logger.info( "\n......Frame start......") #elapsed_time = time.time() - start_time #prepare vfs_model.generate_seed_v_frame_rand_frame(TEST_NODE_LIST) #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 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)): #prepare data if go_on_flag : # get next data logger.info( "onhand {},going to get next data".format(data)) try: 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: # resend last data logger.info( "resend 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) logger.info( "\n===========================\npktno:{}\ndata numer:{}\ndata:{}\n===========================".format(pktno,data_num,data)) pktno += 1 nd_in_response = 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") else: logger.critical("[Seq Number mismatch]") else: logger.critical("[Decode Error] payload fail") else: logger.info( "\n... get broadcast ...") thingy = action(tb, vfs_model, payload,NODE_ID) if thingy: (node_amount, seed, delta, vf_index, alloc_index, in_rand_frame, v_frame) = thingy time_wait_for_my_slot = alloc_index * NODE_SLOT_TIME logger.info( "I will upload at slot {}, wait for {}s".format(alloc_index,time_wait_for_my_slot)) nd_start_time = time.time() nd_in_response = True #vfs_model.send_vfs_pkt( NODE_ID, tb, pkt_size, "**heLLo**{}".pktno, pktno) else: logger.warn( "error during decode VFS_BROADCAST") 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 add_options(normal, expert): """ Adds usrp-specific options to the Options Parser """ common_options.add_options(normal, expert) transmit_path.add_options(normal, expert) receive_path.add_options(normal, expert) # normal.add_option("-T", "--tx-subdev-spec", type="subdev", default=None, # help="select USRP Tx side A or B") expert.add_option( "", "--tx-freq", type="eng_float", default=0.0, help="set transmit frequency to FREQ [default=%default]", metavar="FREQ") normal.add_option("", "--measure", action="store_true", default=False, help="enable troughput measure, usrp disabled") # normal.add_option("", "--dyn-freq", action="store_true", default=False, # help="enable troughput measure, usrp disabled"); expert.add_option("", "--snr", type="eng_float", default=None, help="Simulate AWGN channel") expert.add_option("", "--freqoff", type="eng_float", default=None, help="Simulate frequency offset [default=%default]") expert.add_option( "", "--samplingoffset", type="eng_float", default=None, help="Simulate sampling frequency offset [default=%default]") expert.add_option("", "--multipath", action="store_true", default=False, help="Enable multipath channel") expert.add_option("", "--itu-channel", action="store_true", default=False, help="Enable itu channel model (ported from itpp)") expert.add_option( "", "--online-work", action="store_true", default=False, help= "Force the ofdm transmitter to work during file record [default=%default]" ) # normal.add_option("", "--from-file", type="string", default=None, # help="Sent recorded stream with usrp") # normal.add_option("", "--to-file", type="string", default=None, # help="Record transmitter to disk, not being sent to usrp") expert.add_option( "", "--force-tx-filter", action="store_true", default=False, help="force filter use while transmitting to file or measuring") expert.add_option( "", "--force-rx-filter", action="store_true", default=False, help="force filter use while transmitting to file or measuring") # expert.add_option("", "--nullsink", action="store_true", # default=False, # help="Throw away samples") # normal.add_option("-e", "--interface", type="string", default="eth0", # help="select Ethernet interface, default is eth0") # normal.add_option("-m", "--mac-addr", type="string", default="", # help="select USRP by MAC address, default is auto-select") # normal.add_option("", "--usrp2", action="store_true", default=False, # help="Use USRP2 Interface") expert.add_option("", "--record", action="store_true", default=False, help="Record transmission stream") expert.add_option("", "--berm", action="store_true", default=False, help="BER measurement -> set fixed noise power ") expert.add_option("", "--stations", type="intx", default=1, help="Mobile station count") expert.add_option( "", "--sinr-est", action="store_true", default=False, help="Enable SINR per subcarrier estimation [default=%default]") expert.add_option( "", "--est-preamble", type="int", default=1, help="the number of channel estimation preambles (1 or 2)") normal.add_option("", "--event-rxbaseband", action="store_true", default=False, help="Enable RX baseband via event channel alps") normal.add_option("", "--imgxfer", action="store_true", default=False, help="Enable IMG Transfer mode")
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
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]") usrp_graph.add_options(parser, expert_grp) transmit_path.add_options(parser, expert_grp) receive_path.add_options(parser, expert_grp) blks2.ofdm_mod.add_options(parser, expert_grp) blks2.ofdm_demod.add_options(parser, expert_grp) fusb_options.add_options(expert_grp) (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" # If the user hasn't set the fusb_* parameters on the command line, # pick some values that will reduce latency. if options.fusb_block_size == 0 and options.fusb_nblocks == 0: if realtime: # be more aggressive options.fusb_block_size = gr.prefs().get_long( 'fusb', 'rt_block_size', 1024) options.fusb_nblocks = gr.prefs().get_long('fusb', 'rt_nblocks', 16) else: options.fusb_block_size = gr.prefs().get_long( 'fusb', 'block_size', 4096) options.fusb_nblocks = gr.prefs().get_long('fusb', 'nblocks', 16) #print "fusb_block_size =", options.fusb_block_size #print "fusb_nblocks =", options.fusb_nblocks # instantiate the MAC mac = cs_mac(tun_fd, verbose=True) # build the graph (PHY) tb = usrp_graph(mac.phy_rx_callback, options) 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(fg.txpath.bitrate()),) #print "samples/symbol: %3d" % (fg.txpath.samples_per_symbol(),) #print "interp: %3d" % (fg.txpath.interp(),) #print "decim: %3d" % (fg.rxpath.decim(),) 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(): def fwd_callback(self, packet): """ Invoked by thread associated with the out queue. The resulting packet needs to be sent out using the transmitter flowgraph. The packet could be either a DATA pkt or an ACK pkt. In both cases, only the pkt-hdr needs to be modulated @param packet: the pkt to be forwarded through the transmitter chain """ #print "fwd_callback invoked in tunnel.py" if packet.type() == 1: print "<tunnel.py> tx DATA!" #time.sleep(0.02) #IFS #time.sleep(40) self.tb.txpath.send_pkt(packet, 1, False) elif packet.type() == 2: print "<tunnel.py> tx ACK!" self.tb.txpath.send_pkt(packet, 1, False) else: print "<tunnel.py> unknown pkt type:", packet.type() def rx_callback(ok, payload, valid_timestamp, timestamp_sec, timestamp_frac_sec): global n_rcvd, n_right, batch_size, n_batch_correct, n_correct, n_total_batches n_rcvd += 1 (pktno, ) = struct.unpack('!H', payload[0:2]) if ok: n_right += 1 n_correct += 1 if 1: # count the correct num of batches (works only for batch_size = 2) # if (pktno + 1) % batch_size == 0: n_total_batches += 1 # end of batch # batch_ok = 0 if n_correct == batch_size: n_batch_correct += 1 batch_ok = 1 print "batch ok: %r \t pktno: %d \t n_rcvd: %d \t n_right: %d \t correct_batches: %d \t total_batches: %d \t valid_ts: %d \t sec: %d \t frac_sec: %f" % ( batch_ok, pktno, n_rcvd, n_right, n_batch_correct, n_total_batches, valid_timestamp, timestamp_sec, timestamp_frac_sec) n_correct = 0 def send_pkt(payload='', eof=False): return tb.txpath.send_pkt(payload, 0, eof) def okToTx(): return tb.rxpath.okToTx() def disableOkToTx(): tb.rxpath.disableOkToTx() def permitTx(): tb.txpath.permit_tx() def isEmpty_msgq(): return tb.txpath.isEmpty_msgq() 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) transmit_path.add_options(parser, expert_grp) uhd_transmitter.add_options(parser) digital.ofdm_demod.add_options(parser, expert_grp) receive_path.add_options(parser, expert_grp) uhd_receiver.add_options(parser) (options, args) = parser.parse_args() # build the graph #tb = my_top_block(options) tb = my_top_block(rx_callback, fwd_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(okToTx() == True): if(pktno % 2 == 0): data = (pkt_size) * chr(3 & 0xff) else: data = (pkt_size) * chr(4 & 0xff) #data = (pkt_size - 2) * chr(pktno & 0xff) #data = (pkt_size - 2) * chr(0x34) disableOkToTx(); else: time.sleep(0.01) continue #payload = struct.pack('!H', pktno & 0xffff) + data payload = data send_pkt(payload) n += len(payload) sys.stderr.write('.') #if options.discontinuous and pktno % 5 == 4: # time.sleep(1) pktno += 1 time.sleep(0.65) #time.sleep(0.1) """ # transmits fresh innovative packets, the mapper decides how many packets/batch to send # mapper only sends out packets (innovative or not) when this loop permits it to send. num_flows = 1 if (options.src == 1): while n < nbytes: if ((options.flow == 0) and (n > 0) and (okToTx() == False) and (num_flows == 2)): #if((okToTx() == False)): time.sleep(0.02) continue elif ((options.flow == 1) and (okToTx() == False) and (num_flows == 2)): time.sleep(0.02) continue else: if (isEmpty_msgq() == True): print "Send Fresh Message -- " num_sent = 0 while (num_sent < 2): if (pktno % 2 == 0): data = (pkt_size) * chr(3 & 0xff) else: data = (pkt_size) * chr(4 & 0xff) payload = data send_pkt(payload) n += len(payload) sys.stderr.write('.') pktno += 1 num_sent += 1 if (num_flows == 1): time.sleep(0.65) permitTx() 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) # 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(): mods = modulation_utils.type_1_mods() demods = 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("-v","--verbose", action="store_true", default=False) parser.add_option("-n", "--nodeid", type="int", default=None, help="specify node ID") 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) for mod in mods.values(): mod.add_options(expert_grp) for demod in demods.values(): demod.add_options(expert_grp) fusb_options.add_options(expert_grp) (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" # If the user hasn't set the fusb_* parameters on the command line, # pick some values that will reduce latency. if options.fusb_block_size == 0 and options.fusb_nblocks == 0: if realtime: # be more aggressive options.fusb_block_size = gr.prefs().get_long('fusb', 'rt_block_size', 1024) options.fusb_nblocks = gr.prefs().get_long('fusb', 'rt_nblocks', 16) else: options.fusb_block_size = gr.prefs().get_long('fusb', 'block_size', 4096) options.fusb_nblocks = gr.prefs().get_long('fusb', 'nblocks', 16) #print "fusb_block_size =", options.fusb_block_size #print "fusb_nblocks =", options.fusb_nblocks # instantiate the MAC mac = cs_mac(verbose=False) # 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(),) #print "interp: %3d" % (tb.txpath.interp(),) #print "decim: %3d" % (tb.rxpath.decim(),) tb.rxpath.set_carrier_threshold(options.carrier_threshold) tb.start() # Start executing the flow graph (runs in separate threads)
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) 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 send_pkt(eof=True) tb.wait() # wait for it to finish
def main(): global n_rcvd, n_right n_rcvd = 0 n_right = 0 node_types = {} node_types["head"] = "head" node_types["node"] = "node" mods = {} mods["gmsk"] = "gmsk" mods["bpsk"] = "bpsk" 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) demods = digital.modulation_utils.type_1_demods() mods = digital.modulation_utils.type_1_mods() # 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=demods.keys(), default='psk', help="Select modulation from: %s [default=%%default]" % (', '.join(demods.keys()), )) parser.add_option("-s", "--size", type="eng_float", default=100, help="set packet size [default=%default]") parser.add_option("", "--from-file", default=None, help="input file of samples to demod") #parser.add_option("","--rand-file", action="store_true", default=False, # help="specify yes or no if a random binary data file will be used for the USRP transmitter") parser.add_option( "", "--rand-file", type="intx", default=0, help= "specify yes or no if a random binary data file will be used for the USRP transmitter" ) parser.add_option("", "--node-type", type="choice", choices=node_types.keys(), default="node", help="Select node type from: %s [default=%%default]" % (', '.join(node_types.keys()), )) parser.add_option( "-i", "--node-index", type="intx", default=0, help="Specify the node index in the cluster [default=%default]") ############################### # Options for radio parameters ############################### parser.add_option("-l", "--link-rate", type="eng_float", default=None, help="specify the link data rate") parser.add_option("", "--samp-rate", type="eng_float", default=None, help="specify the sample rate for the USRP") parser.add_option("-f", "--center-freq", type="eng_float", default=None, help="specify the cetner frequency for the USRP") parser.add_option("", "--tx-gain", type="eng_float", default=None, help="specify the tx gain for the USRP") parser.add_option("", "--rx-gain", type="eng_float", default=None, help="specify the rx gain for the USRP") parser.add_option( "-m", "--mod-type", type="choice", choices=mods.keys(), default="gmsk", help="Select the modulation scheme from: %s [default=%%default]" % (', '.join(mods.keys()), )) parser.add_option("", "--diff", action="store_true", default=False, help="specify if the bpsk is differential or not") ################################ # Options for network variants ################################ parser.add_option("", "--rx-only", action="store_true", default=False, help="specify if the node is set as receiver only") parser.add_option("", "--tx-only", action="store_true", default=False, help="specify if the node is set as transmitter only") parser.add_option( "", "--cont-tx", action="store_true", default=False, help= "specify if the node is set as only transmitting continuously, not TDMA" ) for mod in demods.values(): mod.add_options(expert_grp) transmit_path.add_options(parser, expert_grp) (options, args) = parser.parse_args() if len(args) != 0: parser.print_help(sys.stderr) sys.exit(1) # uhd_transmitter.add_options(parser) # build the graph tb = my_top_block(node_types[options.node_type], options.node_index, demods[options.modulation], mods[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 #self.source.u.stop() #time.sleep(10) tb.timer.start()
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) 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(): global n_right n_right = 0 start_time = time.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]") 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) transmit_path.add_options(parser, expert_grp) receive_path.add_options(parser, expert_grp) blks2.ofdm_mod.add_options(parser, expert_grp) blks2.ofdm_demod.add_options(parser, expert_grp) fusb_options.add_options(expert_grp) (options, args) = parser.parse_args () options.carrier_map = SYNC_MAP 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) # linklab, check if the current node is either a sender or a receiver if options.sender and options.receiver: sys.stderr.write("You cannot specify both sender and receiver\n") sys.exit(1) if (not options.sender) and (not options.receiver): sys.stderr.write("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" # If the user hasn't set the fusb_* parameters on the command line, # pick some values that will reduce latency. if options.fusb_block_size == 0 and options.fusb_nblocks == 0: if realtime: # be more aggressive options.fusb_block_size = gr.prefs().get_long('fusb', 'rt_block_size', 1024) options.fusb_nblocks = gr.prefs().get_long('fusb', 'rt_nblocks', 16) else: options.fusb_block_size = gr.prefs().get_long('fusb', 'block_size', 4096) options.fusb_nblocks = gr.prefs().get_long('fusb', 'nblocks', 16) #print "fusb_block_size =", options.fusb_block_size #print "fusb_nblocks =", options.fusb_nblocks # instantiate the MAC # linklab, use ssma instead of csma mac = ss_mac(options.sender, start_time, verbose=True) # update freq_offset options.rx_freq += get_freq_offset() options.tx_freq += get_freq_offset() print "RX frequency", options.rx_freq print "TX frequency", options.tx_freq # build the graph (PHY) tb = usrp_graph(mac.ReceivePacket, options) 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... while 1: pass
def main(): global n_rcvd, n_right n_rcvd = 0 n_right = 0 node_types = {} node_types["head"] = "head" node_types["node"] = "node" 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) demods = digital.modulation_utils.type_1_demods() mods = digital.modulation_utils.type_1_mods() # 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=demods.keys(), default='psk', help="Select modulation from: %s [default=%%default]" % (', '.join(demods.keys()),)) parser.add_option("-s", "--size", type="eng_float", default=100, help="set packet size [default=%default]") parser.add_option("","--from-file", default=None, help="input file of samples to demod") parser.add_option("", "--node-type", type="choice", choices=node_types.keys(), default="node", help="Select node type from: %s [default=%%default]" % (', '.join(node_types.keys()),)) parser.add_option("-i", "--node-index", type="intx", default=0, help="Specify the node index in the cluster [default=%default]") receive_path.add_options(parser, expert_grp) transmit_path.add_options(parser, expert_grp) uhd_sensor.add_options(parser) uhd_transmitter.add_options(parser) for mod in demods.values(): mod.add_options(expert_grp) (options, args) = parser.parse_args () if len(args) != 0: parser.print_help(sys.stderr) sys.exit(1) if options.from_file is None: if (options.sx_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(node_types[options.node_type], options.node_index, demods[options.modulation], mods[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 #self.source.u.stop() #time.sleep(10) tb.timer.start()
def main(): 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("","--discontinuous", action="store_true", default=False, # help="enable discontinous transmission (bursts of 5 packets)") parser.add_option("-s", "--server", default=None, help="competition server IP address") parser.add_option("", "--red", action="store_true", default=False, help="red team") parser.add_option("", "--blue", action="store_true", default=False, help="blue team") #parser.add_option("","--from-file", default=None, # help="use input file for packet contents") #parser.add_option("","--to-file", default=None, # help="Output file for modulated samples") transmit_path.add_options(parser, expert_grp) osmo_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) # Can specify one and only one team if bool(options.red) == bool(options.blue): sys.stderr.write("Which team are you on? Use --red or --blue\n") sys.exit(1) # Must specify an input file or radio frequency #if options.from_file is not None: # source_file = open(options.from_file, 'r') # Strip out the differential option if dbpsk or dqpsk are selected explicitly if (options.modulation == 'dqpsk' or options.modulation == 'dbpsk'): del options.differential transmitter = Transmitter(mods[options.modulation], options) transmitter.print_info() transmitter.run()
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(): 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) 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_USRP options.tx_freq = TXFREQ_USRP options.rx_freq = RXFREQ_USRP options.args = ADDR_USRP 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(): 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) parser.add_option("-p", "--packets", type="int", default=40, help="set number of packets to send [default=%default]") parser.add_option( "", "--address", type="string", default='a', help= "set the address of the node (addresses are a single char) [default=%default]" ) expert_grp.add_option( "-c", "--carrier-threshold", type="eng_float", default=30, help="set carrier detect threshold (dB) [default=%default]") usrp_graph.add_options(parser, expert_grp) transmit_path.add_options(parser, expert_grp) receive_path.add_options(parser, expert_grp) blks2.ofdm_mod.add_options(parser, expert_grp) blks2.ofdm_demod.add_options(parser, expert_grp) cs_mac.add_options(parser, expert_grp) #removed 2011 May 27, MR #fusb_options.add_options(expert_grp) (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) # 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(options) # build the graph (PHY) tb = usrp_graph(mac.phy_rx_callback, options) mac.set_flow_graph(tb) # give the MAC a handle for the PHY print print "address: %s" % (options.address) print 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" # I never start the MAC main loop. We just want to recieve # run the flow graph and wait until the user stops it. tb.start() while 1: if tb.carrier_sensed(): print "Carrier Sensed" #do stuff with the mac measurement results print "this node sent ", mac.sent, " packets" print "this node rcvd ", mac.rcvd, " packets" print "this node rcvd ", mac.rcvd_ok, " packets correctly" print "this node rcvd ", mac.rcvd_data, " data packets correctly"
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(): # 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 add_options(normal, expert): """ Adds usrp-specific options to the Options Parser """ common_options.add_options(normal,expert) transmit_path.add_options(normal,expert) receive_path.add_options(normal,expert) # normal.add_option("-T", "--tx-subdev-spec", type="subdev", default=None, # help="select USRP Tx side A or B") expert.add_option("", "--tx-freq", type="eng_float", default=None, help="set transmit frequency to FREQ [default=%default]", metavar="FREQ") normal.add_option("", "--measure", action="store_true", default=False, help="enable troughput measure, usrp disabled"); # normal.add_option("", "--dyn-freq", action="store_true", default=False, # help="enable troughput measure, usrp disabled"); expert.add_option("", "--snr", type="eng_float", default=None, help="Simulate AWGN channel"); expert.add_option("", "--freqoff", type="eng_float", default=None, help="Simulate frequency offset [default=%default]") expert.add_option("", "--samplingoffset", type="eng_float", default=None, help="Simulate sampling frequency offset [default=%default]") expert.add_option("", "--multipath", action="store_true", default=False, help="Enable multipath channel") expert.add_option("", "--itu-channel", action="store_true", default=False, help="Enable itu channel model (ported from itpp)") expert.add_option("", "--online-work", action="store_true", default=False, help="Force the ofdm transmitter to work during file record [default=%default]") # normal.add_option("", "--from-file", type="string", default=None, # help="Sent recorded stream with usrp") # normal.add_option("", "--to-file", type="string", default=None, # help="Record transmitter to disk, not being sent to usrp") expert.add_option("", "--force-tx-filter", action="store_true", default=False, help="force filter use while transmitting to file or measuring") expert.add_option("", "--force-rx-filter", action="store_true", default=False, help="force filter use while transmitting to file or measuring") expert.add_option("", "--nullsink", action="store_true", default=False, help="Throw away samples") expert.add_option("", "--record", action="store_true", default=False, help="Record transmission stream") expert.add_option("", "--berm", action="store_true", default=False, help="BER measurement -> set fixed noise power ") expert.add_option("", "--stations", type="intx", default=1, help="Mobile station count") expert.add_option("", "--sinr-est", action="store_true", default=False, help="Enable SINR per subcarrier estimation [default=%default]") normal.add_option( "", "--imgxfer", action="store_true", default=False, help="Enable IMG Transfer mode") normal.add_option("", "--coding", action="store_true", default=False, help="Enable channel coding") normal.add_option("", "--nopunct", action="store_true", default=False, help="Disable puncturing/depuncturing") expert.add_option("", "--est-preamble", type="int", default=1, help="the number of channel estimation preambles (1 or 2)");
def add_options(normal, expert): """ Adds usrp-specific options to the Options Parser """ common_tx_rx_usrp_options(normal, expert) transmit_path.add_options(normal, expert) normal.add_option("-T", "--tx-subdev-spec", type="subdev", default=None, help="select USRP Tx side A or B") expert.add_option( "", "--tx-freq", type="eng_float", default=None, help="set transmit frequency to FREQ [default=%default]", metavar="FREQ") normal.add_option("", "--measure", action="store_true", default=False, help="enable troughput measure, usrp disabled") normal.add_option("", "--dyn-freq", action="store_true", default=False, help="enable troughput measure, usrp disabled") expert.add_option("", "--snr", type="eng_float", default=None, help="Simulate AWGN channel") expert.add_option("", "--freqoff", type="eng_float", default=None, help="Simulate frequency offset [default=%default]") expert.add_option( "", "--samplingoffset", type="eng_float", default=None, help="Simulate sampling frequency offset [default=%default]") expert.add_option("", "--berm", action="store_true", default=False, help="Enable static AWGN power for BER measurement") expert.add_option( "", "--online-work", action="store_true", default=False, help= "Force the ofdm transmitter to work during file record [default=%default]" ) normal.add_option("", "--from-file", type="string", default=None, help="Sent recorded stream with usrp") normal.add_option( "", "--to-file", type="string", default=None, help="Record transmitter to disk, not being sent to usrp") expert.add_option( "", "--force-filter", action="store_true", default=False, help="force filter use while transmitting to file or measuring") expert.add_option("", "--nullsink", action="store_true", default=False, help="Throw away samples") normal.add_option("-e", "--interface", type="string", default="eth0", help="select Ethernet interface, default is eth0") normal.add_option( "-m", "--mac-addr", type="string", default="", help="select USRP by MAC address, default is auto-select") normal.add_option("", "--usrp2", action="store_true", default=False, help="Use USRP2 Interface") expert.add_option("", "--record", action="store_true", default=False, help="Record transmission stream") expert.add_option("", "--stations", type="intx", default=1, help="Mobile station count") normal.add_option("", "--coding", action="store_true", default=False, help="Enable channel coding") expert.add_option( "", "--est-preamble", type="int", default=1, help="the number of channel estimation preambles (1 or 2)")
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 add_options(normal, expert): """ Adds usrp-specific options to the Options Parser """ 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) 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]") normal.add_option("-R", "--rx-subdev-spec", type="subdev", default=None, help="select USRP Rx side A or B") normal.add_option( "", "--rx-gain", type="eng_float", default=None, metavar="GAIN", help= "set receiver gain in dB [default=midpoint]. See also --show-rx-gain-range" ) normal.add_option( "", "--show-rx-gain-range", action="store_true", default=False, help="print min and max Rx gain available on selected daughterboard" ) normal.add_option("-v", "--verbose", action="store_true", default=False) expert.add_option("", "--rx-freq", type="eng_float", default=None, help="set Rx frequency to FREQ [default=%default]", metavar="FREQ") expert.add_option( "-d", "--decim", type="intx", default=128, help="set fpga decimation rate to DECIM [default=%default]") expert.add_option( "", "--snr", type="eng_float", default=30, help="set the SNR of the channel in dB [default=%default]") #other necessary options transmit_path.add_options(normal, expert) receive_path.add_options(normal, expert) blks2.ofdm_mod.add_options(normal, expert) blks2.ofdm_demod.add_options(normal, expert) fusb_options.add_options(expert)
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(): 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