Пример #1
0
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
Пример #2
0
def main():
    parser = OptionParser(conflict_handler="resolve")
    expert_grp = parser.add_option_group("Expert")
    rx_top_block.add_options(parser)
    receive_path.add_options(parser, expert_grp)
    uhd_receiver.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 = rx_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('rx_ofdm.dot')
        dot_file = open(file_str, 'w')
        dot_file.write(dot_str)
        dot_file.close()

    try:
        tb.run()
    except [[KeyboardInterrupt]]:
        pass
Пример #3
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)
Пример #4
0
def main():

    global n_rcvd, n_right
        
    n_rcvd = 0
    n_right = 0

    def rx_callback(ok, payload):
        global n_rcvd, n_right
        n_rcvd += 1
        
        if len(payload) > 2:
            (pktno,) = struct.unpack('!H', payload[0:2])
            if ok:
                n_right += 1
        else:
            pktno = -1
            
        print "ok: %r \t pktno: %d \t n_rcvd: %d \t n_right: %d" % (ok, pktno, n_rcvd, n_right)

        if 0:
            printlst = list()
            for x in payload[2:]:
                t = hex(ord(x)).replace('0x', '')
                if(len(t) == 1):
                    t = '0' + t
                printlst.append(t)
            printable = ''.join(printlst)

            print printable
            print "\n"

    parser = OptionParser(option_class=eng_option, conflict_handler="resolve")
    expert_grp = parser.add_option_group("Expert")
    parser.add_option("","--discontinuous", action="store_true", default=False,
                      help="enable discontinuous")
    parser.add_option("","--from-file", default=None,
                      help="input file of samples to demod")

    receive_path.add_options(parser, expert_grp)
    uhd_receiver.add_options(parser)
    digital.ofdm_demod.add_options(parser, expert_grp)

    (options, args) = parser.parse_args ()

    if options.from_file is None:
        if options.rx_freq is None:
            sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
            parser.print_help(sys.stderr)
            sys.exit(1)

    # 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
    tb.wait()                       # wait for it to finish
Пример #5
0
def main():
    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])
        # Xu: Calculate raw BER
        CalcBER(payload[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()

    # 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("","--from-file", default=None,
                      help="input file of samples to demod")

    receive_path.add_options(parser, expert_grp)
    uhd_receiver.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.rx_freq is None:
            sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
            parser.print_help(sys.stderr)
            sys.exit(1)


    # build the graph
    tb = my_top_block(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
    tb.wait()         # wait for it to finish
Пример #6
0
def main():
    parser = OptionParser(conflict_handler="resolve")
    expert_grp = parser.add_option_group("Expert")
    rx_top_block.add_options(parser)
    receive_path.add_options(parser, expert_grp)
    uhd_receiver.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 = rx_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('rx_ofdm.dot')
        dot_file = open(file_str,'w')
        dot_file.write(dot_str)
        dot_file.close()

    try:
        tb.run()
    except [[KeyboardInterrupt]]:
        pass
Пример #7
0
def main():
    global n_rcvd, n_right

    n_rcvd = 0
    n_right = 0
    
    def rx_callback(ok, payload):
        global n_rcvd, n_right
        n_rcvd += 1
        if ok:
            n_right += 1

        tb.audio_tx.msgq().insert_tail(gr.message_from_string(payload))
        
        print "ok = %r  n_rcvd = %4d  n_right = %4d" % (
            ok, n_rcvd, n_right)

    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=demods.keys(), 
                      default='gmsk',
                      help="Select modulation from: %s [default=%%default]"
                            % (', '.join(demods.keys()),))
    parser.add_option("-O", "--audio-output", type="string", default="",
                      help="pcm output device name.  E.g., hw:0,0 or /dev/dsp")
    parser.add_option("","--from-file", default=None,
                      help="input file of samples to demod")
    receive_path.add_options(parser, expert_grp)
    uhd_receiver.add_options(parser)

    for mod in demods.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.stderr)
        sys.exit(1)

    if options.from_file is None:
        if options.rx_freq is None:
            sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
            parser.print_help(sys.stderr)
            sys.exit(1)


    # build the graph
    tb = my_top_block(demods[options.modulation], rx_callback, options)

    r = gr.enable_realtime_scheduling()
    if r != gr.RT_OK:
        print "Warning: Failed to enable realtime scheduling."

    tb.run()
Пример #8
0
def main():
    global n_rcvd, n_right

    n_rcvd = 0
    n_right = 0
    
    def rx_callback(ok, payload):
        global n_rcvd, n_right
        n_rcvd += 1
        if ok:
            n_right += 1

        tb.audio_tx.msgq().insert_tail(gr.message_from_string(payload))
        
        print "ok = %r  n_rcvd = %4d  n_right = %4d" % (
            ok, n_rcvd, n_right)

    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=demods.keys(), 
                      default='gmsk',
                      help="Select modulation from: %s [default=%%default]"
                            % (', '.join(demods.keys()),))
    parser.add_option("-O", "--audio-output", type="string", default="",
                      help="pcm output device name.  E.g., hw:0,0 or /dev/dsp")
    parser.add_option("","--from-file", default=None,
                      help="input file of samples to demod")
    receive_path.add_options(parser, expert_grp)
    uhd_receiver.add_options(parser)

    for mod in demods.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.stderr)
        sys.exit(1)

    if options.from_file is None:
        if options.rx_freq is None:
            sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
            parser.print_help(sys.stderr)
            sys.exit(1)


    # build the graph
    tb = my_top_block(demods[options.modulation], rx_callback, options)

    r = gr.enable_realtime_scheduling()
    if r != gr.RT_OK:
        print "Warning: Failed to enable realtime scheduling."

    tb.run()
Пример #9
0
def main():
    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)

    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=demods.keys(), 
                      default='psk',
                      help="Select modulation from: %s [default=%%default]"
                            % (', '.join(demods.keys()),))
    parser.add_option("","--from-file", default=None,
                      help="input file of samples to demod")

    receive_path.add_options(parser, expert_grp)
    uhd_receiver.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.rx_freq is None:
            sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
            parser.print_help(sys.stderr)
            sys.exit(1)


    # build the graph
    tb = my_top_block(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
    tb.wait()         # wait for it to finish
Пример #10
0
def main():
    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=demods.keys(), 
                      default='psk',
                      help="Select modulation from: %s [default=%%default]"
                            % (', '.join(demods.keys()),))
    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="input file of samples to demod")

    receive_path.add_options(parser, expert_grp)
    osmo_receiver.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)
        
    # 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 None:
    if options.rx_freq is None:
        sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
        sys.stderr.write("Use --help to see all options\n")
        sys.exit(1)
        
    # Must specify a server
    if options.server is None:
        sys.stderr.write("You must specify -s ADDRESS or --server ADDRESS\n")
        sys.exit(1)

    # Strip out the differential option if dbpsk or dqpsk are selected explicitly
    if (options.modulation == 'dqpsk' or options.modulation == 'dbpsk'):
        del options.differential
        
    # Fire it up
    receiver = Receiver(demods[options.modulation], options)
    receiver.print_info()
    receiver.run()
Пример #11
0
def main():

    global n_rcvd, n_right

    n_rcvd = 0
    n_right = 0

    def rx_callback(ok, payload):
        global n_rcvd, n_right
        n_rcvd += 1
        (pktno, ) = struct.unpack('!H', payload[0:2])
        if ok:
            n_right += 1
        print "ok: %r \t pktno: %d \t n_rcvd: %d \t n_right: %d" % (
            ok, pktno, n_rcvd, n_right)

        if 0:
            printlst = list()
            for x in payload[2:]:
                t = hex(ord(x)).replace('0x', '')
                if (len(t) == 1):
                    t = '0' + t
                printlst.append(t)
            printable = ''.join(printlst)

            print printable
            print "\n"

    usage = "usage: %prog [options] host"
    parser = OptionParser(usage=usage,
                          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")

    my_top_block.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)

    (options, args) = parser.parse_args()
    address = args[0]

    # build the graph
    tb = my_top_block(address, 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
    tb.wait()  # wait for it to finish
Пример #12
0
def main():

    global n_rcvd, n_right

    n_rcvd = 0
    n_right = 0

    def rx_callback(ok, payload):
        global n_rcvd, n_right
        n_rcvd += 1
        (pktno,) = struct.unpack('!H', payload[0:2])
        if ok:
            n_right += 1
        print "ok: %r \t pktno: %d \t n_rcvd: %d \t n_right: %d" % (ok, pktno, n_rcvd, n_right)

        if 0:
            printlst = list()
            for x in payload[2:]:
                t = hex(ord(x)).replace('0x', '')
                if(len(t) == 1):
                    t = '0' + t
                printlst.append(t)
            printable = ''.join(printlst)

            print printable
            print "\n"

    parser = OptionParser(option_class=eng_option, conflict_handler="resolve")
    expert_grp = parser.add_option_group("Expert")
    parser.add_option("","--discontinuous", action="store_true", default=False,
                      help="enable discontinuous")
    parser.add_option("","--from-file", default=None,
                      help="input file of samples to demod")

    receive_path.add_options(parser, expert_grp)
    uhd_receiver.add_options(parser)
    digital.ofdm_demod.add_options(parser, expert_grp)

    (options, args) = parser.parse_args ()

    if options.from_file is None:
        if options.rx_freq is None:
            sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
            parser.print_help(sys.stderr)
            sys.exit(1)

    # build the graph
    print options
    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
    tb.wait()                       # wait for it to finish
Пример #13
0
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()
Пример #14
0
def main():

    global n_rcvd, n_right

    n_rcvd = 0
    n_right = 0

    def rx_callback(ok, payload):
        global n_rcvd, n_right
        n_rcvd += 1
        if ok:
            print payload
            n_right += 1
            print "right:", n_right
        #print "ok: %r \t pktno: %d \t n_rcvd: %d \t n_right: %d" % (ok, pktno, n_rcvd, n_right)

    parser = OptionParser(option_class=eng_option, conflict_handler="resolve")
    expert_grp = parser.add_option_group("Expert")
    parser.add_option("",
                      "--discontinuous",
                      action="store_true",
                      default=False,
                      help="enable discontinuous")
    parser.add_option("",
                      "--from-file",
                      default=None,
                      help="input file of samples to demod")

    parser.add_option("",
                      "--freq",
                      type="int",
                      dest="rx_freq",
                      default=500000000,
                      help="set rx freq")
    receive_path.add_options(parser, expert_grp)
    #uhd_receiver.add_options(parser)
    digital.ofdm_demod.add_options(parser, expert_grp)

    (options, args) = parser.parse_args()

    if options.from_file is None:
        if options.rx_freq is None:
            sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
            parser.print_help(sys.stderr)
            sys.exit(1)

    # 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
    tb.wait()  # wait for it to finish
Пример #15
0
def main():

    global n_rcvd, n_right
        
    n_rcvd = 0
    n_right = 0

    def rx_callback(ok, payload):
        global n_rcvd, n_right
        n_rcvd += 1
        (pktno,) = struct.unpack('!H', payload[0:2])
        if ok:
            n_right += 1
        print "ok: %r \t pktno: %d \t n_rcvd: %d \t n_right: %d" % (ok, pktno, n_rcvd, n_right)

        if 0:
            printlst = list()
            for x in payload[2:]:
                t = hex(ord(x)).replace('0x', '')
                if(len(t) == 1):
                    t = '0' + t
                printlst.append(t)
            printable = ''.join(printlst)

            print printable
            print "\n"

    usage = "usage: %prog [options] host"
    parser = OptionParser(usage=usage, 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")

    my_top_block.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)

    (options, args) = parser.parse_args ()
    address = args[0]

    # build the graph
    tb = my_top_block(address, 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
    tb.wait()                       # wait for it to finish
Пример #16
0
def main():
    global file
    
    def rx_callback(ok, payload):
        if ok:
            file.write(payload)

    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=demods.keys(),
                      default='psk',
                      help="Select modulation from :%s [default=%%default]"
                            % (', '.join(demods.keys()),))

    parser.add_option("-s", "--size", type="eng_float", default=1500,
                      help="set packet size [default=%default]")
    parser.add_option("","--samples-file", default=None,
                      help="Output file for modulated samples")
    parser.add_option("","--to-file", default=None,
                      help="Output file for demodulated contents")

    receive_path.add_options(parser, expert_grp)

    for mod in demods.values():
        mod.add_options(expert_grp)
 
    (options, args) = parser.parse_args()

    if len(args) != 0:
       parser.print_help()
       sys.exit(1)

    if options.to_file is not None:
        file = open(options.to_file, "w+")  
 
    tb = loop_top_block(demods[options.modulation], options, rx_callback)

    # 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()
    tb.wait()
Пример #17
0
    def __init__(self,
                 midFreq,
                 fft_len,
                 occupied_len,
                 cp_len,
                 dinter,
                 callback=None):
        if midFreq == None or fft_len == None or \
            occupied_len == None or cp_len == None:
            print 'param is not ok!'
            return

        if callback == None:
            callback = self.rx_callback
        args = ['-d', str(dinter), '-R', '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)
        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(args)

        self.tb = my_top_block(callback, options)

        r = gr.enable_realtime_scheduling()
        if r != gr.RT_OK:
            print 'Warning: failed to enable realtime scheduling'

        self.n_rcvd = 0
        self.n_right = 0

        print 'rx init ok!'
Пример #18
0
    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]")
Пример #19
0
    def __init__(self, midFreq, fft_len, occupied_len, cp_len, dinter, callback = None):
        if midFreq == None or fft_len == None or \
            occupied_len == None or cp_len == None:
            print 'param is not ok!'
            return

        if callback == None:
            callback = self.rx_callback
        args = ['-d', str(dinter), '-R', '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)
        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 (args)
        
        self.tb = my_top_block(callback, options)

        r = gr.enable_realtime_scheduling()
        if r != gr.RT_OK:
            print 'Warning: failed to enable realtime scheduling'

        self.n_rcvd = 0
        self.n_right = 0
        
        print 'rx init ok!'
Пример #20
0
def main():

    global n_rcvd, n_right
        
    n_rcvd = 0
    n_right = 0

    def rx_callback(ok, payload):
        global n_rcvd, n_right
        n_rcvd += 1
        (pktno,) = struct.unpack('!H', payload[0:2])
        if ok:
            n_right += 1
        print "ok: %r \t pktno: %d \t n_rcvd: %d \t n_right: %d" % (ok, pktno, n_rcvd, n_right)



    parser = OptionParser(option_class=eng_option, conflict_handler="resolve")
    expert_grp = parser.add_option_group("Expert")

    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 ()


    # 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
    tb.wait()                       # wait for it to finish
Пример #21
0
    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")
Пример #22
0
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"
Пример #23
0
def main():

    global n_rcvd, n_right, sock
    
    UDP_IP = "localhost"
    UDP_PORT = 5005
    n_rcvd = 0
    n_right = 0

    sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # UDP
    def rx_callback(ok, payload):
        global n_rcvd, n_right, sock
        n_rcvd += 1
        (pktno,) = struct.unpack('!H', payload[0:2])
        data  = payload[2:]
        if ok:
            n_right += 1
        print "ok: %r \t pktno: %d \t n_rcvd: %d \t n_right: %d \t n_right: %d" % (ok, pktno, n_rcvd, n_right, len(data))
        #if len(data)!=1316:
            #return
        #sock.sendto(data, (UDP_IP, UDP_PORT))
        

        if 0:
            printlst = list()
            for x in payload[2:]:
                t = hex(ord(x)).replace('0x', '')
                if(len(t) == 1):
                    t = '0' + t
                printlst.append(t)
            printable = ''.join(printlst)

            print printable
            print "\n"
            
    def rx_callback_msb(ok, payload):
        global n_rcvd, n_right, sock
        n_rcvd += 1
        (pktno,) = struct.unpack('!H', payload[0:2])
        data  = payload[2:]
        if ok:
            n_right += 1
        print "MSB ok: %r \t pktno: %d \t n_rcvd: %d \t n_right: %d \t n_right: %d" % (ok, pktno, n_rcvd, n_right, len(data))
        #print "\n\n\n"
        #print ''.join(format(ord(x), 'b') for x in data)
        #print "\n\n\n"
        #if len(data)!=1316:
            #return
        #sock.sendto(data, (UDP_IP, UDP_PORT))
        

        if 0:
            printlst = list()
            for x in payload[2:]:
                t = hex(ord(x)).replace('0x', '')
                if(len(t) == 1):
                    t = '0' + t
                printlst.append(t)
            printable = ''.join(printlst)

            print printable
            print "\n"
            
    def rx_callback_lsb(ok, payload):
        global n_rcvd, n_right, sock
        n_rcvd += 1
        (pktno,) = struct.unpack('!H', payload[0:2])
        data  = payload[2:]
        if ok:
            n_right += 1
        print "LSB ok: %r \t pktno: %d \t n_rcvd: %d \t n_right: %d \t n_right: %d" % (ok, pktno, n_rcvd, n_right, len(data))
        #if len(data)!=1316:
            #return
        #sock.sendto(data, (UDP_IP, UDP_PORT))
        

        if 0:
            printlst = list()
            for x in payload[2:]:
                t = hex(ord(x)).replace('0x', '')
                if(len(t) == 1):
                    t = '0' + t
                printlst.append(t)
            printable = ''.join(printlst)

            print printable
            print "\n"

    parser = OptionParser(option_class=eng_option, conflict_handler="resolve")
    expert_grp = parser.add_option_group("Expert")
    
    """
    parser.add_option("","--discontinuous", action="store_true", default=False,
                      help="enable discontinuous")
    parser.add_option("","--from-file", default=None,
                      help="input file of samples to demod")


    """
    
    parser.add_option("-a", "--args", type="string", default="",
                          help="Device args, [default=%default]")
    parser.add_option("-A", "--antenna", type="string", default=None,
                      help="Select RX antenna where appropriate")
    parser.add_option("-s", "--samp-rate", type="eng_float", default=None,
                      help="Set sample rate (bandwidth), minimum by default")
    parser.add_option("-f", "--center-freq", type="eng_float", default=None,
                      help="Set frequency to FREQ", metavar="FREQ")
    parser.add_option("-c", "--freq-corr", type="eng_float", default=None,
                      help="Set frequency correction (ppm)")
    parser.add_option("-g", "--gain", type="eng_float", default=None,
                      help="Set gain in dB (default is midpoint)")
    parser.add_option("-G", "--gains", type="string", default=None,
                      help="Set named gain in dB, name:gain,name:gain,...")
    parser.add_option("-r", "--record", type="string", default="/tmp/name-f%F-s%S-t%T.cfile",
                      help="Filename to record to, available wildcards: %S: sample rate, %F: center frequency, %T: timestamp, Example: /tmp/name-f%F-s%S-t%T.cfile")
    parser.add_option("", "--dc-offset-mode", type="int", default=None,
                      help="Set the RX frontend DC offset correction mode")
    parser.add_option("", "--iq-balance-mode", type="int", default=None,
                      help="Set the RX frontend IQ imbalance correction mode")
    parser.add_option("-W", "--waterfall", action="store_true", default=False,
                      help="Enable waterfall display")
    parser.add_option("-F", "--fosphor", action="store_true", default=False,
                      help="Enable fosphor display")
    parser.add_option("-S", "--oscilloscope", action="store_true", default=False,
                      help="Enable oscilloscope display")
    parser.add_option("", "--avg-alpha", type="eng_float", default=1e-1,
                      help="Set fftsink averaging factor, default=[%default]")
    parser.add_option("", "--averaging", action="store_true", default=False,
                      help="Enable fftsink averaging, default=[%default]")
    parser.add_option("", "--ref-scale", type="eng_float", default=1.0,
                      help="Set dBFS=0dB input value, default=[%default]")
    parser.add_option("", "--fft-size", type="int", default=1024,
                      help="Set number of FFT bins [default=%default]")
    parser.add_option("", "--fft-rate", type="int", default=30,
                      help="Set FFT update rate, [default=%default]")
    parser.add_option("-v", "--verbose", action="store_true", default=False,
                      help="Use verbose console output [default=%default]")
    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 ()


    # build the graph
    tb = my_top_block(rx_callback,rx_callback_msb, rx_callback_lsb, options)

    r = gr.enable_realtime_scheduling()
    if r != gr.RT_OK:
        print "Warning: failed to enable realtime scheduling"

    tb.start()                      # start flow graph
    tb.wait()                       # wait for it to finish
Пример #24
0
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()
Пример #25
0
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)
Пример #26
0
def main():

    print "ssma.py"

    global n_right
    n_right = 0

    start_time = time.time()
    print "Start Time " , start_time

    parser = OptionParser (option_class=eng_option, conflict_handler="resolve")
    expert_grp = parser.add_option_group("Expert")

    parser.add_option("-m", "--modulation", type="choice", choices=['bpsk', 'qpsk'],
                      default='bpsk',
                      help="Select modulation from: bpsk, qpsk [default=%%default]")
    expert_grp.add_option("-c", "--carrier-threshold", type="eng_float", default=40,
                      help="set carrier detect threshold (dB) [default=%default]")
    expert_grp.add_option("", "--nc-filter", action="store_true", default=False)


    parser.add_option("-v","--verbose", action="store_true", default=False)


    # linklab, add option to indicate sender or receiver
    parser.add_option("-s","--sender", action="store_true", default=False)
    parser.add_option("-r","--receiver", action="store_true", default=False)


    usrp_graph.add_options(parser, expert_grp)
    
    uhd_transmitter.add_options(parser)
    #uhd_receiver.add_options(parser)
    transmit_path.add_options(parser, expert_grp)
    receive_path.add_options(parser, expert_grp)
    
    gr_papyrus.ofdm.ofdm_mod.add_options(parser, expert_grp)
    gr_papyrus.ofdm.ofdm_demod.add_options(parser, expert_grp)
    
    (options, args) = parser.parse_args ()
    options.carrier_map = SYNC_MAP
    print "Added options"
    print options

    if len(args) != 0:
        parser.print_help(sys.stderr)
        sys.exit(1)

    if options.rx_freq is None or options.tx_freq is None:
        print ("You must specify -f FREQ or --freq FREQ\n")
        parser.print_help(sys.stderr)
        sys.exit(1)
    
    # linklab, check if the current node is either a sender or a receiver
    if options.sender and options.receiver:
        print ("You cannot specify both sender and receiver\n")
        sys.exit(1)
    if (not options.sender) and (not options.receiver):
        print ("You must specify either sender or receiver\n")
        sys.exit(1)
    #

    # Attempt to enable realtime scheduling
    r = gr.enable_realtime_scheduling()
    if r == gr.RT_OK:
        realtime = True
    else:
        realtime = False
        print "Note: failed to enable realtime scheduling"
	
    # instantiate the MAC
	# linklab, use ssma instead of csma
	mac = ss_mac(options.sender, start_time, verbose=options.verbose)

    print "RX frequency", options.rx_freq
    print "TX frequency", options.tx_freq

    # build the graph (PHY)
    tb = usrp_graph(mac.ReceivePacket, options)
    print "returned from usrp_graph"

    mac.set_flow_graph(tb)    # give the MAC a handle for the PHY

    #if fg.txpath.bitrate() != fg.rxpath.bitrate():
    #    print "WARNING: Transmit bitrate = %sb/sec, Receive bitrate = %sb/sec" % (
    #        eng_notation.num_to_str(fg.txpath.bitrate()),
    #        eng_notation.num_to_str(fg.rxpath.bitrate()))

    print "modulation:     %s"   % (options.modulation,)
    print "freq:           %s"      % (eng_notation.num_to_str(options.tx_freq))
    # print "bitrate:        %sb/sec" % (eng_notation.num_to_str(tb.txpath.bitrate()),)
    # print "samples/symbol: %3d" % (tb.txpath.samples_per_symbol(),)
    # print "interp:         %3d" % (tb.txpath.interp(),)
    # print "decim:          %3d" % (tb.rxpath.decim(),)


    tb.start()    # Start executing the flow graph (runs in separate threads)

    mac.main_loop()    # don't expect this to return...
Пример #27
0
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
Пример #28
0
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
Пример #29
0
def main():
    global n_rcvd, n_right, per_wait, last_n_rcvd, freq_offset

    per_wait = 0.2
    freq_offset = 625000

    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)

    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=demods.keys(), 
                      default='dqpsk',
                      help="Select modulation from: %s [default=%%default]"
                            % (', '.join(demods.keys()),))
    parser.add_option("","--from-file", default=None,
                      help="input file of samples to demod")

    receive_path.add_options(parser, expert_grp)
    uhd_receiver.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.rx_freq is None:
            sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
            parser.print_help(sys.stderr)
            sys.exit(1)


    # build the graph
    tb = my_top_block(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

    last_n_rcvd = n_rcvd
    cur_freq_offset = freq_offset
    tb.source.set_freq(options.rx_freq+cur_freq_offset)
    
    while 1:
        global n_rcvd, n_right, per_wait, last_n_rcvd, freq_offset
        
        time.sleep(per_wait)
        if last_n_rcvd == n_rcvd:
            if cur_freq_offset > 0:
                cur_freq_offset = 0-freq_offset
            else:
                cur_freq_offset = freq_offset

            print "Switching frequency to %d\n" % (options.rx_freq+cur_freq_offset)
            tb.source.set_freq(options.rx_freq+cur_freq_offset)

        else:
            print "Not switching frequencies since we are still receiving\n"
            last_n_rcvd = n_rcvd

    tb.wait()         # wait for it to finish
Пример #30
0
def main():

    global n_rcvd, n_right

    n_rcvd = 0
    n_right = 0

    # linklab, add parameters for interger freq offset (int_fo), fractional freq offset (frac_fo)
    # SINR estimation in time domain (time_sinr), SINR estimation in freq domain
    def rx_callback(ok, payload, int_fo, frac_fo, time_sinr, freq_sinr):
        global n_rcvd, n_right
        n_rcvd += 1
        try:
            (pktno, ) = struct.unpack('!H', payload[0:2])
        except:
            pktno = 1
        if ok:
            n_right += 1
            freq_offset = int_fo + frac_fo / math.pi
            print "freq offset: %+.2f(subcarriers) \t SINR: %.2f(time domain), %.2f(freq domain)" % (
                freq_offset, time_sinr, freq_sinr)
        # linklab, calculate packet loss rate and error rate
        try:
            pkt_loss = (1 - n_rcvd / float(pktno)) * 100
            pkt_err = (1 - n_right / float(pktno)) * 100
        except:
            pkt_loss = 100
            pkt_err = 100

        # linklab, print packet info
        print "ok: %r \t pktno: %d \t n_rcvd: %d \t n_right: %d \t pkt_loss: %.2f%% \t pkt_err: %.2f%%" % (
            ok, pktno, n_rcvd, n_right, pkt_loss, pkt_err)

        if 0:
            printlst = list()
            for x in payload[2:]:
                t = hex(ord(x)).replace('0x', '')
                if (len(t) == 1):
                    t = '0' + t
                printlst.append(t)
            printable = ''.join(printlst)

            print printable
            print "\n"

    parser = OptionParser(option_class=eng_option, conflict_handler="resolve")
    expert_grp = parser.add_option_group("Expert")
    parser.add_option("",
                      "--discontinuous",
                      action="store_true",
                      default=False,
                      help="enable discontinuous")

    my_top_block.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)
    fusb_options.add_options(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
    tb.wait()  # wait for it to finish
Пример #31
0
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"
Пример #32
0
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
Пример #33
0
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():

    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"
Пример #35
0
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)
Пример #36
0
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()
Пример #37
0
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
Пример #38
0
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
Пример #39
0
def main():
    global n_rcvd, n_right, start_time, stop_rcv
    
    TIMEOUT = 60 # 60sec for hurdle 2
    n_rcvd = 0
    n_right = 0
    start_time = 0
    mstr_cnt = 0
    stop_rcv = 0
    


    TCP_IP='10.10.0.51'
    TCP_PORT=5125
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try: 
       s.connect((TCP_IP, TCP_PORT))
    except socket.error as e:
       print "Error connecting to the packet sink: %s" %e.strerror
       return
    
    def rx_callback(ok, payload):
        global n_rcvd, n_right, start_time, stop_rcv
        (pktno,crc,sn) = struct.unpack('!HLL', payload[0:10])
        n_rcvd += 1
        if ok:
            n_right += 1
            try:            
               data = s.recv(4) # if a ready packet is received
               s.send(payload[2:])
            except socket.error as e:
               print "Socket error: %s" %e.strerror
               stop_rcv = 1
               return
            if data.__len__() == 0:
               print "Connection closed"
               stop_rcv = 1
               return
            if n_right == 1:
               start_time = time.time()
            if n_right == 2000:
               t = time.time() - start_time              
               print"Mod : %5s, Rate : %8d, Time for 2000 pkts : %f sec\n" %(options.modulation, options.bitrate, t)
               stop_rcv = 1;
              

            
        if options.verbose:
           print "ok = %5s  pktno = %4d  n_rcvd = %4d  n_right = %4d" %(
            ok, pktno, n_rcvd, n_right)

    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=demods.keys(), 
                      default='psk',
                      help="Select modulation from: %s [default=%%default]"
                            % (', '.join(demods.keys()),))
    parser.add_option("","--from-file", default=None,
                      help="input file of samples to demod")

    receive_path.add_options(parser, expert_grp)
    uhd_receiver.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.rx_freq is None:
            sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
            parser.print_help(sys.stderr)
            sys.exit(1)


    # build the graph
    tb = my_top_block(demods[options.modulation], rx_callback, options)

    r = gr.enable_realtime_scheduling()
    if r != gr.RT_OK:
        print "Warning: Failed to enable realtime scheduling."

    # log parameters to OML
    cmd1 = "/root/OML/omlcli --out h2_benchmark --line \""
    cmd1 = cmd1 + " rx-freq=" + str(options.rx_freq)
    cmd1 = cmd1 + " modulation=" + str(options.modulation)
    cmd1 = cmd1 + " rx-gain=" + str(options.rx_gain)
    cmd1 = cmd1 + " bitrate=" + str(options.bitrate)
    cmd1 = cmd1 + " sps=" + str(options.samples_per_symbol)
    cmd1 = cmd1 + " hostname=" + socket.gethostname()
    cmd1 = cmd1 + "\""

    from subprocess import os
    os.system(cmd1)


    tb.start()        # start flow graph
   # tb.wait()         # wait for it to finish
    
    while mstr_cnt < TIMEOUT*1000:
       if stop_rcv == 1:
          break;
       mstr_cnt = mstr_cnt + 1
       time.sleep(0.001)

    if stop_rcv == 0:
       print "Receiver timed out, received %d packets successfully in %d sec" %(n_right, TIMEOUT)

    s.close()
Пример #40
0
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
Пример #41
0
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()
Пример #42
0
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)
Пример #43
0
def main():

    global n_rcvd, n_right

    n_rcvd = 0
    n_right = 0

    parser = OptionParser(option_class=eng_option, conflict_handler="resolve")
    parser.add_option(
        "",
        "--vr-configuration",
        type="int",
        default=1,
        help=
        "Default configuration for VR RX (matches the configuration of TX) [default=%default]"
    )

    expert_grp = parser.add_option_group("Expert")

    expert_grp.add_option(
        "-p",
        "--port",
        type="intx",
        default=23451,
        help=
        "set UDP socket port number to ouput the received data  [default=%default]"
    )
    expert_grp.add_option("-p",
                          "--rpc-port",
                          type="intx",
                          default=12345,
                          help="set UDP socket port number [default=%default]")
    expert_grp.add_option("",
                          "--host",
                          default="127.0.0.1",
                          help="set host IP address [default=%default]")

    receive_path.add_options(expert_grp, expert_grp)
    uhd_receiver.add_options(expert_grp)
    digital.ofdm_demod.add_options(expert_grp, expert_grp)
    (options, args) = parser.parse_args()

    options_vr1 = dict2obj({
        'id': 0,
        'tx_amplitude': 0.125,
        'freq': hydra_center_frequency + vr1_initial_shift,
        'bandwidth': 1e6,
        'gain': 15,
        'snr': options.snr,
        'file': None,
        'buffersize': 4072,
        'modulation': 'qpsk',
        'fft_length': 1024,
        'occupied_tones': 800,
        'cp_length': 4,
        'host': options.host,
        'rpc_port': options.rpc_port,
        'port': options.port,
        'args': options.args,
        'lo_offset': options.lo_offset,
        'spec': options.spec,
        'antenna': options.antenna,
        'clock_source': options.clock_source,
        'verbose': False,
        'log': False
    })
    options_vr2 = dict2obj({
        'id': 1,
        'tx_amplitude': 0.125,
        'freq': hydra_center_frequency + vr2_initial_shift,
        'bandwidth': 200e3,
        'gain': 15,
        'snr': options.snr,
        'file': None,
        'buffersize': 4072,
        'modulation': 'bpsk',
        'fft_length': 64,
        'occupied_tones': 48,
        'cp_length': 2,
        'host': options.host,
        'rpc_port': options.rpc_port,
        'port': options.port + 1,
        'args': options.args,
        'lo_offset': options.lo_offset,
        'spec': options.spec,
        'antenna': options.antenna,
        'clock_source': options.clock_source,
        'verbose': False,
        'log': False
    })

    vr_configuration = [options_vr1, options_vr2]
    if options.vr_configuration is not None:
        options = vr_configuration[options.vr_configuration - 1]

    if options.freq is None:
        sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
        parser.print_help(sys.stderr)
        sys.exit(1)

    cs = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    def rx_callback_vr2(ok, payload):
        global n_rcvd, n_right, g_pkt_history
        (pktno, ) = struct.unpack('!H', payload[0:2])

        n_rcvd += 1
        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)

        data = payload[2:10]
        cs.sendto(data, (options.host, options.port))
        g_pkt_history.append(PktHistory(len(data), time.time()))

    def rx_callback_vr1(ok, payload):
        global n_rcvd, n_right, g_pkt_history, pkt_buffer, n_fec
        MAX_RET = 2
        (pktno, ) = struct.unpack('!H', payload[0:2])

        n_rcvd += 1
        if ok:
            n_right += 1

        if (pktno == 1):
            if len(pkt_buffer) > 0 or ok:
                if not ok and len(pkt_buffer) > 0:
                    n_fec += 1

                data = payload[2:] if ok else pkt_buffer[0]

                cs.sendto(data, (options.host, options.port))
                g_pkt_history.append(PktHistory(len(data), time.time()))
                pkt_buffer = []
        else:
            if ok:
                pkt_buffer.append(payload[2:])

        print "ok: %r \t pktno: %d \t n_rcvd: %d \t n_right: %d \t n_fec: %d" % (
            ok, pktno, n_rcvd, n_right, n_fec)

    # build the graph
    tb = my_top_block(rx_callback_vr2 if options.id == 1 else rx_callback_vr1,
                      options)

    r = gr.enable_realtime_scheduling()
    if r != gr.RT_OK:
        print "Warning: failed to enable realtime scheduling"

    tb.start()  # start flow graph
    tb.wait()  # wait for it to finish
    tb.xmlrpc_server.shutdown()
Пример #44
0
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
Пример #45
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)
Пример #46
0
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
Пример #47
0
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
Пример #48
0
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():

    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
Пример #50
0
def main():
    parser = OptionParser(conflict_handler="resolve")
    expert_grp = parser.add_option_group("Expert")

    ofdm_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_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('~/omnilog/benchmark_ofdm.dot')
            filetx = os.path.expanduser('benchmark_ofdm.dot')
            dot_file = open(filetx, 'w')
            dot_file.write(string_benchmark)
            dot_file.close()

        runtime.run()
        try:
            tx.txpath._control._id_source.ready()
        except:
            pass

    except KeyboardInterrupt:
        runtime.stop()
        # somewhat messy hack
        #    try:
        #      rx.rxs_msgq.flush()
        #      rx.rxs_msgq.insert_tail(gr.message(1))
        #    except:
        #      print "Could not flush msgq"
        #      pass
        runtime.wait()

    if options.measure:
        print "min", tx.m.get_min()
        print "max", tx.m.get_max()
        print "avg", tx.m.get_avg()
Пример #51
0
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
Пример #52
0
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
Пример #53
0
def main(top_block_cls=ofdm_multichannel_receiver, options=None):

    global n_rcvd, n_right, printout

    n_rcvd = 0
    n_right = 0
    printout = False

    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
        if printout:
            print "ok: %r \t pktno: %d \t n_rcvd: %d \t n_right: %d" % (
                ok, pktno, n_rcvd, n_right)

        if 0:
            printlst = list()
            for x in payload[2:]:
                t = hex(ord(x)).replace('0x', '')
                if (len(t) == 1):
                    t = '0' + t
                printlst.append(t)
            printable = ''.join(printlst)

            if printout:
                print printable
                print "\n"

    ################################################
    # SETUP options
    # {'from_file': None, 'verbose': False, 'antenna': None, 'discontinuous': False,
    # 'args': 'addr=192.168.20.2', 'tx_freq': 900000000.0, 'fft_length': 512,
    # 'modulation': 'bpsk', 'bandwidth': 500000.0, 'snr': 30.0, 'log': False,
    # 'clock_source': None, 'lo_offset': 0, 'occupied_tones': 200,
    # 'cp_length': 128, 'freq': None, 'rx_freq': 900000000.0, 'spec': None, 'rx_gain': None}
    # options['from_file'] = None
    # options.verbose = False
    # options.antenna = None
    # options.discontinuous = False
    # options.args = 'addr=192.168.20.2'
    # options.tx_freq = 900000000
    # options.fft_length = 512
    # options.modulation = 'bpsk'
    # options.bandwidth = 500000
    # options.snr = 30
    # options.log = False
    # options.clock_source = None
    # options.lo_offset = 0
    # options.occupied_tones = 200
    # options.cp_length = 128
    # options.freq = None
    # options.rx_freq = 900000000
    # options.spec = None
    # options.rx_gain = None
    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")

    receive_path.add_options(parser, expert_grp)
    uhd_receiver.add_options(parser)
    digital.ofdm_demod.add_options(parser, expert_grp)

    (options, args) = parser.parse_args()

    if options.from_file is None:
        if options.rx_freq is None:
            options.rx_freq = 900000000

    ################################################
    if gr.enable_realtime_scheduling() != gr.RT_OK:
        print "Error: failed to enable real-time scheduling."

    from distutils.version import StrictVersion
    if StrictVersion(Qt.qVersion()) >= StrictVersion("4.5.0"):
        style = gr.prefs().get_string('qtgui', 'style', 'raster')
        Qt.QApplication.setGraphicsSystem(style)
    qapp = Qt.QApplication(sys.argv)

    tb = top_block_cls(rx_callback, options)
    tb.start()
    tb.show()

    def quitting():
        tb.stop()
        tb.wait()

    qapp.connect(qapp, Qt.SIGNAL("aboutToQuit()"), quitting)
    qapp.exec_()
Пример #54
0
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)
Пример #55
0
def main():
    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])
        data = payload[2:]
        n_rcvd += 1
        if ok:
            n_right += 1
            if options.server:
                sock.sendall(data)

        print "ok = %5s  pktno = %4d  n_rcvd = %4d  n_right = %4d" % (
            ok, pktno, n_rcvd, n_right)

    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=demods.keys(),
                      default='psk',
                      help="Select modulation from: %s [default=%%default]" %
                      (', '.join(demods.keys()), ))
    parser.add_option("",
                      "--from-file",
                      default=None,
                      help="input file of samples to demod")
    parser.add_option("",
                      "--server",
                      action="store_true",
                      default=False,
                      help="To take data from the server")

    receive_path.add_options(parser, expert_grp)
    uhd_receiver.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.rx_freq is None:
            sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
            parser.print_help(sys.stderr)
            sys.exit(1)

    # connect to server
    if options.server:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_address = ('10.0.0.200', 50001)
        print >> sys.stderr, 'connecting to %s port %s' % server_address
        sock.connect(server_address)

    # build the graph
    tb = my_top_block(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
    tb.wait()  # wait for it to finish

    if options.server:
        sock.close()
Пример #56
0
def main():
    global n_rcvd, n_right, start_time, start, once
    once = 1
    n_rcvd = 0
    n_right = 0

    def rx_callback(ok, payload):
        global n_rcvd, n_right
        try:
            (pktno, ) = struct.unpack('!H', payload[0:2])
            data = payload[2:]
            n_rcvd += 1
            if ok:
                n_right += 1

                if options.server:
                    sock.sendall(data)
            current = time.time() - start
        except:
            print "except"

#print "current time = %f ok = %5s  pktno = %4d  n_rcvd = %4d  n_right = %4d" % (current, ok, pktno, n_rcvd, n_right)
        omlDb.inject("packets", ("received", n_rcvd))
        omlDb.inject("packets", ("correct", n_right))

    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=demods.keys(),
                      default='gfsk',
                      help="Select modulation from: %s [default=%%default]" %
                      (', '.join(demods.keys()), ))
    parser.add_option("",
                      "--from-file",
                      default=None,
                      help="input file of samples to demod")
    parser.add_option("-E",
                      "--exp-id",
                      type="string",
                      default="test",
                      help="specify the experiment ID")
    parser.add_option("-N",
                      "--node-id",
                      type="string",
                      default="rx",
                      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")

    receive_path.add_options(parser, expert_grp)
    uhd_receiver.add_options(parser)

    for mod in demods.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.stderr)
        sys.exit(1)

    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)

    # connect to server
    if options.server:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        #    	server_address = ('10.0.1.200', 50001)
        server_address = ('10.0.1.200', options.port)
        print >> sys.stderr, 'connecting to %s port %s' % server_address
        sock.connect(server_address)

    # build the graph
    tb = my_top_block(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
    start = time.time()

    while 1:
        current = time.time() - start
        if current >= 5:
            symbol_rate = options.bitrate / demods[options.modulation](
                **args).bits_per_symbol()
            tb.source.set_sample_rate(symbol_rate, options.samples_per_symbol)

            options.rx_freq += 0.75e6
            tb.source.set_freq(options.rx_freq, options.lo_offset)
            break
    #print "FROM OPTIONS.........", tb.source._freq
    tb.wait()  # wait for it to finish

    if options.server:
        sock.close()
Пример #57
0
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
Пример #58
0
def main():
    global n_rcvd, n_right, pktno

    n_rcvd = 0
    n_right = 0
    pktno = 1
    
    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)


    demods = modulation_utils2.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=demods.keys(), 
                      default='dbpsk2',
                      help="Select modulation from: %s [default=%%default]"
                            % (', '.join(demods.keys()),))

    my_top_block.add_options(parser, expert_grp)
    receive_path.add_options(parser, expert_grp)
    usrp_options.add_rx_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.rx_freq is None:
        sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
        parser.print_help(sys.stderr)
        sys.exit(1)


    # build the graph
    tb = my_top_block(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

    if(options.gui):
        tb.qapp.exec_()
    else:
        tb.wait()         # wait for it to finish
Пример #59
0
def main():

    print "ssma.py"

    global n_right
    n_right = 0

    start_time = time.time()
    print "Start Time ", start_time

    parser = OptionParser(option_class=eng_option, conflict_handler="resolve")
    expert_grp = parser.add_option_group("Expert")

    parser.add_option(
        "-m",
        "--modulation",
        type="choice",
        choices=['bpsk', 'qpsk'],
        default='bpsk',
        help="Select modulation from: bpsk, qpsk [default=%%default]")
    expert_grp.add_option(
        "-c",
        "--carrier-threshold",
        type="eng_float",
        default=40,
        help="set carrier detect threshold (dB) [default=%default]")
    expert_grp.add_option("",
                          "--nc-filter",
                          action="store_true",
                          default=False)

    parser.add_option("-v", "--verbose", action="store_true", default=False)

    # linklab, add option to indicate sender or receiver
    parser.add_option("-s", "--sender", action="store_true", default=False)
    parser.add_option("-r", "--receiver", action="store_true", default=False)

    usrp_graph.add_options(parser, expert_grp)

    uhd_transmitter.add_options(parser)
    #uhd_receiver.add_options(parser)
    transmit_path.add_options(parser, expert_grp)
    receive_path.add_options(parser, expert_grp)

    gr_papyrus.ofdm.ofdm_mod.add_options(parser, expert_grp)
    gr_papyrus.ofdm.ofdm_demod.add_options(parser, expert_grp)

    (options, args) = parser.parse_args()
    options.carrier_map = SYNC_MAP
    print "Added options"
    print options

    if len(args) != 0:
        parser.print_help(sys.stderr)
        sys.exit(1)

    if options.rx_freq is None or options.tx_freq is None:
        print("You must specify -f FREQ or --freq FREQ\n")
        parser.print_help(sys.stderr)
        sys.exit(1)

    # linklab, check if the current node is either a sender or a receiver
    if options.sender and options.receiver:
        print("You cannot specify both sender and receiver\n")
        sys.exit(1)
    if (not options.sender) and (not options.receiver):
        print("You must specify either sender or receiver\n")
        sys.exit(1)
    #

    # Attempt to enable realtime scheduling
    r = gr.enable_realtime_scheduling()
    if r == gr.RT_OK:
        realtime = True
    else:
        realtime = False
        print "Note: failed to enable realtime scheduling"

        # instantiate the MAC
        # linklab, use ssma instead of csma
        mac = ss_mac(options.sender, start_time, verbose=options.verbose)

    print "RX frequency", options.rx_freq
    print "TX frequency", options.tx_freq

    # build the graph (PHY)
    tb = usrp_graph(mac.ReceivePacket, options)
    print "returned from usrp_graph"

    mac.set_flow_graph(tb)  # give the MAC a handle for the PHY

    #if fg.txpath.bitrate() != fg.rxpath.bitrate():
    #    print "WARNING: Transmit bitrate = %sb/sec, Receive bitrate = %sb/sec" % (
    #        eng_notation.num_to_str(fg.txpath.bitrate()),
    #        eng_notation.num_to_str(fg.rxpath.bitrate()))

    print "modulation:     %s" % (options.modulation, )
    print "freq:           %s" % (eng_notation.num_to_str(options.tx_freq))
    # print "bitrate:        %sb/sec" % (eng_notation.num_to_str(tb.txpath.bitrate()),)
    # print "samples/symbol: %3d" % (tb.txpath.samples_per_symbol(),)
    # print "interp:         %3d" % (tb.txpath.interp(),)
    # print "decim:          %3d" % (tb.rxpath.decim(),)

    tb.start()  # Start executing the flow graph (runs in separate threads)

    mac.main_loop()  # don't expect this to return...