Example #1
0
 def add_options(normal, expert):
     """
     Adds usrp-specific options to the Options Parser
     """
     normal.add_option("",
                       "--infile",
                       type="string",
                       help="select input file to TX from")
     normal.add_option(
         "-c",
         "--channel",
         type="eng_float",
         default=17,
         help="Set 802.15.4 Channel to listen on channel %default",
         metavar="FREQ")
     normal.add_option("-v",
                       "--verbose",
                       action="store_true",
                       default=False)
     normal.add_option("-W",
                       "--bandwidth",
                       type="eng_float",
                       default=4000e3,
                       help="set symbol bandwidth [default=%default]")
     normal.add_option("-t", "--threshold", type="int", default=-1)
     expert.add_option(
         "",
         "--log",
         action="store_true",
         default=False,
         help="Log all parts of flow graph to files (CAUTION: lots of data)"
     )
     uhd_receiver.add_options(normal)
Example #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
Example #3
0
def get_options(demods):
    parser = OptionParser(option_class=eng_option, conflict_handler="resolve")
    parser.add_option("", "--from-file", default=None,
                      help="input file of samples to demod")
    parser.add_option("-m", "--modulation", type="choice", choices=list(demods.keys()),
                      default='psk',
                      help="Select modulation from: %s [default=%%default]"
                            % (', '.join(list(demods.keys())),))
    parser.add_option("-r", "--bitrate", type="eng_float", default=250e3,
                      help="Select modulation bit rate (default=%default)")
    parser.add_option("-S", "--samples-per-symbol", type="float", default=2,
                      help="set samples/symbol [default=%default]")
    if not parser.has_option("--verbose"):
        parser.add_option("-v", "--verbose",
                          action="store_true", default=False)
    if not parser.has_option("--log"):
        parser.add_option("", "--log", action="store_true", default=False,
                          help="Log all parts of flow graph to files (CAUTION: lots of data)")

    uhd_receiver.add_options(parser)

    demods = digital.modulation_utils.type_1_demods()
    for mod in list(demods.values()):
        mod.add_options(parser)

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

    return (options, args)
Example #4
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
Example #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
        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
Example #6
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
def get_options(demods):
    parser = OptionParser(option_class=eng_option, conflict_handler="resolve")
    parser.add_option("","--from-file", default=None,
                      help="input file of samples to demod")
    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("-r", "--bitrate", type="eng_float", default=250e3,
                      help="Select modulation bit rate (default=%default)")
    parser.add_option("-S", "--samples-per-symbol", type="float", default=2,
                      help="set samples/symbol [default=%default]")
    if not parser.has_option("--verbose"):
        parser.add_option("-v", "--verbose", action="store_true", default=False)
    if not parser.has_option("--log"):
        parser.add_option("", "--log", action="store_true", default=False,
                      help="Log all parts of flow graph to files (CAUTION: lots of data)")

    uhd_receiver.add_options(parser)

    demods = digital.modulation_utils.type_1_demods()
    for mod in demods.values():
        mod.add_options(parser)
		      
    (options, args) = parser.parse_args()
    if len(args) != 0:
        parser.print_help()
        sys.exit(1)
	
    return (options, args)
def add_options(parser, expert):
	add_freq_option(parser)
	uhd_receiver.add_options(parser)
	receive_path.receive_path.add_options(parser, expert)
	expert.add_option("", "--rx-freq", type="eng_float", default=None,
					help="set Rx frequency to FREQ [default=%default]", metavar="FREQ")
	parser.add_option("-v", "--verbose", action="store_true", default=False)
Example #9
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
Example #10
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()
Example #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
        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()
Example #12
0
    def add_options(normal, expert):
        """
        Adds usrp-specific options to the Options Parser
        """
        uhd_receiver.add_options(normal)

        add_freq_option(normal)
        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)
        # linklab,  add options to specify which USRP to sue
        normal.add_option(
            "-w",
            "--which",
            type="int",
            default=0,
            help="select which USRP (0, 1, ...) default is %default",
            metavar="NUM")

        expert.add_option("",
                          "--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]")
Example #13
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
Example #14
0
 def add_options(normal, expert):
     normal.add_option("",
                       "--infile",
                       type="string",
                       help="select input file")
     normal.add_option("",
                       "--outfile",
                       type="string",
                       help="select output file (raw)")
     normal.add_option("",
                       "--txdata",
                       type="string",
                       help="source data file")
     normal.add_option("",
                       "--rxdata",
                       type="string",
                       help="data file (demodulated)")
     normal.add_option(
         "",
         "--char",
         type="eng_float",
         default=0,
         metavar="CAMPL",
         help=
         "output is char data that should be scaled by CAMPL/128: [default=%default]"
     )
     normal.add_option(
         "",
         "--snrdata",
         type="string",
         help="per packet snr data file (- print out, . scope out)")
     normal.add_option(
         "",
         "--snrmode",
         type="int",
         default=0,
         help=
         "0 - per symbol, 1 - per packet, 2 - per bin [default=%default]")
     normal.add_option("-v",
                       "--verbose",
                       action="store_true",
                       default=False)
     normal.add_option("-W",
                       "--bandwidth",
                       type="eng_float",
                       default=500e3,
                       help="set symbol bandwidth [default=%default]")
     expert.add_option(
         "",
         "--log",
         action="store_true",
         default=False,
         help="Log all parts of flow graph to files (CAUTION: lots of data)"
     )
     uhd_receiver.add_options(normal)
     #usrp2.add_options(normal)
     ofdm_rxtx.RX.add_options(normal, expert)
Example #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"

    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
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()
Example #17
0
def add_options(parser, expert):
    add_freq_option(parser)
    uhd_receiver.add_options(parser)
    receive_path.receive_path.add_options(parser, expert)
    expert.add_option("",
                      "--rx-freq",
                      type="eng_float",
                      default=None,
                      help="set Rx frequency to FREQ [default=%default]",
                      metavar="FREQ")
    parser.add_option("-v", "--verbose", action="store_true", default=False)
Example #18
0
    def add_options(normal, expert):
        """
        Adds usrp-specific options to the Options Parser
        """
        uhd_receiver.add_options(normal)

        add_freq_option(normal)
        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)
        # linklab,  add options to specify which USRP to sue
        normal.add_option(
            "-w",
            "--which",
            type="int",
            default=0,
            help="select which USRP (0, 1, ...) default is %default",
            metavar="NUM",
        )

        expert.add_option(
            "",
            "--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]"
        )
 def add_options(normal, expert):
   normal.add_option("", "--infile", type="string",
                     help="select input file")
   normal.add_option("", "--outfile", type="string",
                     help="select output file (raw)")
   normal.add_option("", "--rxdata", type="string",
                     help="data file (demodulated)")
   normal.add_option("-v", "--verbose", action="store_true", default=False)
   normal.add_option("-W", "--bandwidth", type="eng_float", default=1e6,
                     help="set symbol bandwidth [default=%default]")
   expert.add_option("", "--log", action="store_true", default=False,
                     help="Log all parts of flow graph to files (CAUTION: lots of data)")
   expert.add_option("", "--profile", action="store_true", default=False,
                     help="enable gr-ctrlport to monitor performance")
   uhd_receiver.add_options(normal)
   ofdm_receive_path.add_options(normal, expert)
 def add_options(normal, expert):
     """
     Adds usrp-specific options to the Options Parser
     """
     normal.add_option("", "--infile", type="string",
                       help="select input file to TX from")
     normal.add_option ("-c", "--channel", type="eng_float", default=17,
                       help="Set 802.15.4 Channel to listen on channel %default", metavar="FREQ")
     normal.add_option("-v", "--verbose", action="store_true", default=False)
     normal.add_option("-W", "--bandwidth", type="eng_float",
                       default=4000e3,
                       help="set symbol bandwidth [default=%default]")
     normal.add_option ("-t", "--threshold", type="int", default=-1)
     expert.add_option("", "--log", action="store_true", default=False,
                       help="Log all parts of flow graph to files (CAUTION: lots of data)")
     uhd_receiver.add_options(normal)
Example #21
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   

    # Create Options Parser:
    parser = OptionParser (option_class=eng_option, conflict_handler="resolve")
    expert_grp = parser.add_option_group("Expert")

    parser.add_option("-s", "--server", type="string", default='idb2',
                      help="server hosting the packet server/sink")
    parser.add_option("-o", "--port", type="int", default='5125',
                      help="packet sink tcp port")
    parser.add_option("-i", "--timeout", type="int", default='300',help='receive timeout(sec)')
    parser.add_option("","--from-file", default=None,
                      help="input file of samples to demod")

    uhd_receiver.add_options(parser)

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

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

    tb.start()
    tb.wait()         # wait for it to finish
Example #22
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]")
 def add_options(normal, expert):
   normal.add_option("", "--rx-infile", type="string",
                     help="select RX input file (raw)")
   normal.add_option("", "--rx-outfile", type="string",
                     help="select RX output file (raw)")
   normal.add_option("", "--tx-outfile", type="string", default=None,
                     help="select TX output file (raw)")
   normal.add_option("-W", "--bandwidth", type="eng_float", default=1e6,
                     help="set symbol bandwidth [default=%default]")  
   normal.add_option("", "--tx-amplitude", type="eng_float", default=0.1, metavar="AMPL",
                     help="set transmitter digital amplitude: 0 <= AMPL < 1.0 [default=%default]")
   expert.add_option("-v", "--verbose", action="store_true", default=False)
   expert.add_option("", "--profile", action="store_true", default=False,
                     help="enable ctrlport_monitor and ctrlport_monitor_performance")
   expert.add_option("", "--logfile", action="store_true", default=False,
                     help="log all usrp samples")
   uhd_transmitter.add_options(normal)
   uhd_receiver.add_options(normal)
   transmit_path.ofdm_transmit_path.add_options(normal, expert)
   receive_path.ofdm_receive_path.add_options(normal, expert)
Example #24
0
def main():

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

    uhd_transmitter.add_options(parser)
    uhd_receiver.add_options(parser)

    (options, args) = parser.parse_args()

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

    # build the graph
    tb = my_top_block(options)

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

    tb.run()
Example #25
0
def main():

    # Create Options Parser:
    parser = OptionParser (option_class=eng_option, conflict_handler="resolve")
    expert_grp = parser.add_option_group("Expert")

    uhd_receiver.add_options(parser)
    uhd_transmitter.add_options(parser)

    (options, args) = parser.parse_args ()

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

    # build the graph
    tb = my_top_block(options)

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

    tb.start()        # start flow graph
    tb.wait()         # wait for it to finish
Example #26
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
Example #27
0
 def add_options(normal, expert):
   normal.add_option("", "--infile", type="string",
                     help="select input file")
   normal.add_option("", "--outfile", type="string",
                     help="select output file (raw)")
   normal.add_option("", "--txdata", type="string",
                     help="source data file")
   normal.add_option("", "--rxdata", type="string",
                     help="data file (demodulated)")
   normal.add_option("", "--char", type="eng_float", default=0, metavar="CAMPL",
                     help="output is char data that should be scaled by CAMPL/128: [default=%default]")
   normal.add_option("", "--snrdata", type="string",
                     help="per packet snr data file (- print out, . scope out)")
   normal.add_option("", "--snrmode", type="int", default=0,
                     help="0 - per symbol, 1 - per packet, 2 - per bin [default=%default]")
   normal.add_option("-v", "--verbose", action="store_true", default=False)
   normal.add_option("-W", "--bandwidth", type="eng_float",
                         default=500e3,
                         help="set symbol bandwidth [default=%default]")
   expert.add_option("", "--log", action="store_true", default=False,
                     help="Log all parts of flow graph to files (CAUTION: lots of data)")
   uhd_receiver.add_options(normal)
   #usrp2.add_options(normal)
   ofdm_rxtx.RX.add_options(normal, expert)
Example #28
0
def main():
    parser = OptionParser(option_class=eng_option, conflict_handler="resolve")
    parser.add_option(
        "",
        "--vr-configuration",
        type="string",
        default=None,
        help=
        "Default configuration for VR RX (matches the configuration of TX) [default=%default]"
    )
    parser.add_option(
        "",
        "--from-file",
        type="string",
        default=None,
        help="Specify a file source if USRP is not used [default=%default]")

    radio_lte.add_options(parser)
    radio_nbiot.add_options(parser)
    uhd_receiver.add_options(parser)
    (options, args) = parser.parse_args()

    if options.vr_configuration not in bc.VIRTUAL_RADIO:
        print("Invalid virtual radios. Valid radios are: %s" %
              (",".join(bc.VIRTUAL_RADIO)))
        return 1

    def generic_rx_callback(ok, payload):
        (pktno, ) = struct.unpack('!H', payload[0:2])
        print "ok: %r \t pktno: %d \t len: %d, \t timestamp: %f" % (
            ok, pktno, len(payload).time.time())

    # build the graph
    tb = my_top_block(generic_rx_callback, options)
    tb.start()  # start flow graph
    tb.wait()  # wait for it to finish
Example #29
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()
Example #30
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
Example #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)
    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
Example #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]")

    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
Example #33
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)
Example #34
0
def main():

    global n_rcvd, n_right, v_frame, mean_delta, next_tx_ts, stop_rx_ts, ps_end_ts, alloc_index, vf_index,\
        listen_only_to

    n_rcvd = 0
    n_right = 0
    mean_delta = 0
    next_tx_ts = 0
    stop_rx_ts = 0
    ps_end_ts = 0
    alloc_index = -1
    vf_index = -1
    listen_only_to = []
    wrong_pktno = 0xFF00
    v_frame = ''
    vf_len = 8

    ps_model = PerfectScheme(PacketType.PS_BROADCAST.index,
                             PacketType.PS_PKT.index, NODE_SLOT_TIME)
    vfs_model = VirtualFrameScheme(PacketType.VFS_BROADCAST.index,
                                   PacketType.VFS_PKT.index, NODE_SLOT_TIME)

    def send_beacon_pkt(my_tb, pkt_size, pkt_no):  # BS only
        # payload = prefix + now + beacon + dummy

        payload_prefix = struct.pack('!H', pkt_no & 0xffff)
        beacon = struct.pack('!H', PacketType.BEACON.index & 0xffff)
        data_size = len(payload_prefix) + TIMESTAMP_LEN + len(beacon)
        dummy = (pkt_size - data_size) * chr(pkt_no & 0xff)
        now_timestamp = my_tb.sink.get_time_now().get_real_secs()
        now_timestamp_str = '{:.3f}'.format(now_timestamp)
        payload = payload_prefix + now_timestamp_str + beacon + dummy
        my_tb.txpath.send_pkt(payload)
        logger.info("{} broadcast BEACON - {}".format(
            str(datetime.fromtimestamp(now_timestamp)), pkt_no))

    # Deprecated
    # def send_resp_beacon_pkt(my_tb, pkt_size, pkt_no):     # Node only
    #     # payload = prefix + now + respond_beacon + node_id + dummy
    #
    #     payload_prefix = struct.pack('!H', pkt_no & 0xffff)
    #     respond_beacon = struct.pack('!H', PacketType.RESPOND_BEACON.index & 0xffff)
    #     data_size = len(payload_prefix) + TIMESTAMP_LEN + len(respond_beacon) + NODE_ID_LEN
    #     dummy = (pkt_size - data_size) * chr(pkt_no & 0xff)
    #     now_timestamp = my_tb.sink.get_time_now().get_real_secs()
    #     now_timestamp_str = '{:.3f}'.format(now_timestamp)
    #     payload = payload_prefix + now_timestamp_str + respond_beacon + NODE_ID + dummy
    #     my_tb.txpath.send_pkt(payload)
    #     logger.info("{} send RESPOND_BEACON - {}".format(str(datetime.fromtimestamp(now_timestamp)), pkt_no))
    #
    #     # TODO: how to track rtt?
    #     # Keep rtt_list size limit
    #     rtt_list.append(now_timestamp)
    #     if len(rtt_list) > MAX_RTT_AMT:
    #         rtt_list.pop(0)

    def do_every_beacon(interval,
                        _send_pkt_func,
                        my_tb,
                        pkt_size,
                        max_pkt_amt,
                        iteration=1):
        # For other functions to check these variables
        global my_thread, my_iteration
        my_iteration = iteration

        if iteration < max_pkt_amt:
            # my_thread = threading.Timer(interval, do_every_beacon,
            #                             [interval, _send_pkt_func, my_tb, pkt_amt, 0
            #                                 if iteration == 0 else iteration + 1])
            my_thread = threading.Timer(interval, do_every_beacon, [
                interval, _send_pkt_func, my_tb, pkt_size, max_pkt_amt,
                max_pkt_amt if iteration >= max_pkt_amt else iteration + 1
            ])
            my_thread.start()
        # execute func
        _send_pkt_func(my_tb, pkt_size, iteration)

    def do_every_protocol_bs(interval,
                             _send_pkt_func,
                             my_tb,
                             pkt_size,
                             node_amt,
                             max_pkt_amt,
                             iteration=1):
        # For other functions to check these variables
        global my_thread, my_iteration
        my_iteration = iteration

        if iteration < max_pkt_amt:
            my_thread = threading.Timer(interval, do_every_protocol_bs, [
                interval, _send_pkt_func, my_tb, pkt_size, node_amt,
                max_pkt_amt,
                max_pkt_amt if iteration >= max_pkt_amt else iteration + 1
            ])
            my_thread.start()
        # execute func
        _send_pkt_func(my_tb, pkt_size, node_amt, iteration)

    def do_every_protocol_node(interval,
                               _send_pkt_func,
                               node_id,
                               my_tb,
                               pkt_size,
                               node_data,
                               max_pkt_amt,
                               iteration=1):
        # For other functions to check these variables
        global my_thread, my_iteration
        my_iteration = iteration

        if iteration < max_pkt_amt:
            my_thread = threading.Timer(interval, do_every_protocol_node, [
                interval, _send_pkt_func, node_id, my_tb, pkt_size, node_data,
                max_pkt_amt,
                max_pkt_amt if iteration >= max_pkt_amt else iteration + 1
            ])
            my_thread.start()
        # execute func
        _send_pkt_func(node_id, my_tb, pkt_size, node_data, iteration)

    def rx_bs_callback(ok, payload):  # For BS
        global n_rcvd, n_right, mean_delta, next_tx_ts, stop_rx_ts, nodes_sync_delta, listen_only_to

        n_rcvd += 1

        (pktno, ) = struct.unpack('!H', payload[0:2])
        # Filter out incorrect pkt
        if pktno >= wrong_pktno:
            logger.warning("wrong pktno {}. Drop pkt!".format(pktno))
            return

        try:
            pkt_timestamp_str = payload[2:2 + TIMESTAMP_LEN]
            pkt_timestamp = float(pkt_timestamp_str)
        except:
            logger.warning("Timestamp {} is not a float. Drop pkt!".format(
                pkt_timestamp_str))
            return

        now_timestamp = rx_tb.source.get_time_now().get_real_secs()
        # now_timestamp_str = '{:.3f}'.format(now_timestamp)
        delta = now_timestamp - pkt_timestamp  # +ve: Node earlier; -ve: BS earlier
        if not -5 < delta < 5:
            logger.warning(
                "Delay out-of-range: {}, timestamp {}. Drop pkt!".format(
                    delta, pkt_timestamp_str))
            return

        (pkt_type, ) = struct.unpack(
            '!H', payload[2 + TIMESTAMP_LEN:2 + TIMESTAMP_LEN + 2])
        # if pkt_type not in [PacketType.RESPOND_BEACON.index, PacketType.PS_PKT.index]:
        if pkt_type not in [PacketType.PS_PKT.index, PacketType.VFS_PKT.index]:
            logger.warning("Invalid pkt_type {}. Drop pkt!".format(pkt_type))
            return
        if listen_only_to and pkt_type not in listen_only_to:
            str_listen_only_to = [PacketType[x].key for x in listen_only_to]
            logger.warning(
                "Interest only in pkt_type {}, not {}. Drop pkt!".format(
                    str_listen_only_to, PacketType[pkt_type].key))
            return

        # Deprecated
        # if pkt_type == PacketType.RESPOND_BEACON.index:
        #     node_id = payload[2+TIMESTAMP_LEN+2:2+TIMESTAMP_LEN+2+NODE_ID_LEN]
        #     if nodes_sync_delta.get(node_id) is None:
        #         nodes_sync_delta[node_id] = []
        #     nodes_sync_delta[node_id].append(delta)
        #     # Keep nodes_sync_delta in size limit
        #     if len(nodes_sync_delta[node_id]) > MAX_DELTA_AMT:
        #         nodes_sync_delta[node_id].pop(0)
        #     mean_delta = numpy.mean(nodes_sync_delta[node_id])
        #
        #     next_tx_ts = now_timestamp + 0.5 - COMMAND_DELAY
        #
        #     logger.info("{} BS recv RESPOND_BEACON from node {}. Node time: {}, Avg delay: {}".format(
        #         str(datetime.fromtimestamp(now_timestamp)), node_id, str(datetime.fromtimestamp(pkt_timestamp)),
        #         mean_delta))
        #     # logger.debug("Node {} len {} {}".format(node_id, len(nodes_sync_delta[node_id]), nodes_sync_delta[node_id]))
        #     # logger.debug("Node {}: {}".format(node_id, nodes_sync_delta[node_id]))
        #     return

        if pkt_type == PacketType.PS_PKT.index:
            for i, tpl in enumerate(ps_model.nodes_expect_time):
                node_id, begin_at, end_at = tpl
                if begin_at <= now_timestamp <= end_at:
                    logger.info(
                        "{} ({}) [Slot {}: Node {} Session] BS recv PS_PKT {}, data: {}"
                        .format(str(datetime.fromtimestamp(now_timestamp)),
                                now_timestamp, i, node_id, pktno,
                                ps_model.get_node_data(payload)))
                    return

            logger.info(
                "{} ({}) [No slot/session] BS recv PS_PKT {}, data: {}".format(
                    str(datetime.fromtimestamp(now_timestamp)), now_timestamp,
                    pktno, ps_model.get_node_data(payload)))
            # Last timestamp for PS_PKT session
            #next_tx_ts = ps_model.nodes_expect_time[-1][-1] + 0.2   # add some delay
            return

        if pkt_type == PacketType.VFS_PKT.index:
            for i, tpl in enumerate(vfs_model.nodes_expect_time):
                node_id, begin_at, end_at = tpl
                if begin_at <= now_timestamp <= end_at:
                    logger.info(
                        "{} ({}) [Slot {}: Node {} Session] BS recv VFS_PKT {}, data: {}"
                        .format(str(datetime.fromtimestamp(now_timestamp)),
                                now_timestamp, i, node_id, pktno,
                                vfs_model.get_node_data(payload)))
                    return

            logger.info(
                "{} ({}) [No slot/session] BS recv VFS_PKT {}, data: {}".
                format(str(datetime.fromtimestamp(now_timestamp)),
                       now_timestamp, pktno, vfs_model.get_node_data(payload)))
            # Last timestamp for VFS_PKT session
            #next_tx_ts = vfs_model.nodes_expect_time[-1][-1] + 0.2   # add some delay
            return

    def rx_node_callback(ok, payload):  # For Node
        global n_rcvd, n_right, mean_delta, next_tx_ts, stop_rx_ts, ps_end_ts, alloc_index, vf_index, \
            listen_only_to

        n_rcvd += 1

        (pktno, ) = struct.unpack('!H', payload[0:2])
        # Filter out incorrect pkt
        if pktno >= wrong_pktno:
            logger.warning("Wrong pktno {}. Drop pkt!".format(pktno))
            return

        try:
            pkt_timestamp_str = payload[2:2 + TIMESTAMP_LEN]
            pkt_timestamp = float(pkt_timestamp_str)
        except:
            logger.warning("Timestamp {} is not a float. Drop pkt!".format(
                pkt_timestamp_str))
            return

        now_timestamp = rx_tb.source.get_time_now().get_real_secs()
        # now_timestamp_str = '{:.3f}'.format(now_timestamp)
        delta = now_timestamp - pkt_timestamp  # +ve: BS earlier; -ve: Node earlier
        if not -5 < delta < 5:
            logger.warning(
                "Delay out-of-range: {}, timestamp {}. Drop pkt!".format(
                    delta, pkt_timestamp_str))
            return

        (pkt_type, ) = struct.unpack(
            '!H', payload[2 + TIMESTAMP_LEN:2 + TIMESTAMP_LEN + 2])
        if pkt_type not in [
                PacketType.BEACON.index, PacketType.ACK_RESPOND.index,
                PacketType.PS_BROADCAST.index, PacketType.VFS_BROADCAST.index
        ]:
            logger.warning("Invalid pkt_type {}. Drop pkt!".format(pkt_type))
            return
        if listen_only_to and pkt_type not in listen_only_to:
            str_listen_only_to = [PacketType[x].key for x in listen_only_to]
            logger.warning(
                "Interest only in pkt_type {}, not {}. Drop pkt!".format(
                    str_listen_only_to, PacketType[pkt_type].key))
            return

        if pkt_type == PacketType.BEACON.index:
            delta_list.append(delta)
            # Keep delta_list in size limit
            if len(delta_list) > MAX_DELTA_AMT:
                delta_list.pop(0)
            mean_delta = numpy.mean(delta_list)
            # mean_delta_str = '{:07.3f}'.format(delta)
            # Adjust time if needed
            if not -0.05 <= mean_delta <= 0.05:
                rx_tb.source.set_time_now(uhd.time_spec(pkt_timestamp))
                now_timestamp = rx_tb.source.get_time_now().get_real_secs()
                logger.info("Adjust time... New time: {}".format(
                    str(datetime.fromtimestamp(now_timestamp))))

            stop_rx_ts = now_timestamp + 0.5 - COMMAND_DELAY
            # Hack: for RX2400
            if pktno >= MAX_PKT_AMT - 10:
                stop_rx_ts -= 0.3

            logger.info(
                "{} Node recv BEACON {}. BS time: {}, Avg delay: {}".format(
                    str(datetime.fromtimestamp(now_timestamp)), pktno,
                    str(datetime.fromtimestamp(pkt_timestamp)), mean_delta))
            # logger.debug("stop_rx_ts {}".format(str(datetime.fromtimestamp(stop_rx_ts))))
            return

        if pkt_type == PacketType.PS_BROADCAST.index:
            node_amount = ps_model.get_node_amount(payload)
            seed = ps_model.get_seed(payload)
            alloc_index = ps_model.compute_alloc_index(node_amount, NODE_ID,
                                                       seed)
            try:
                begin_timestamp_str = ps_model.get_begin_time_str(payload)
                begin_timestamp = float(begin_timestamp_str)
            except:
                logger.warning(
                    "begin_timestamp {} is not a float. Drop pkt!".format(
                        begin_timestamp_str))
                return

            stop_rx_ts = now_timestamp + 0.4
            # TODO: Duo to various delays, adjust a bit to before firing round up second
            next_tx_ts = begin_timestamp + (NODE_SLOT_TIME *
                                            alloc_index) - TRANSMIT_DELAY
            # Each node time slot at NODE_SLOT_TIME seconds
            ps_end_ts = begin_timestamp + (NODE_SLOT_TIME * node_amount)

            logger.info(
                "{} Node recv PS_BROADCAST {}, BS time {}, Total {}, Seed {}, Index {}, Delay {}"
                .format(str(datetime.fromtimestamp(now_timestamp)), pktno,
                        str(datetime.fromtimestamp(pkt_timestamp)),
                        node_amount, seed, alloc_index, delta))
            # logger.debug("begin {}, stop_rx_ts {}, next_tx_ts {}, ps_end_ts {}".format(
            #     str(datetime.fromtimestamp(begin_timestamp)), str(datetime.fromtimestamp(stop_rx_ts)),
            #     str(datetime.fromtimestamp(next_tx_ts)), str(datetime.fromtimestamp(ps_end_ts))))
            return

        if pkt_type == PacketType.VFS_BROADCAST.index:
            node_amount = vfs_model.get_node_amount(payload)
            seed = ps_model.get_seed(payload)
            try:
                begin_timestamp_str = vfs_model.get_begin_time_str(payload)
                begin_timestamp = float(begin_timestamp_str)
            except:
                logger.warning(
                    "begin_timestamp {} is not a float. Drop pkt!".format(
                        begin_timestamp_str))
                return
            try:
                v_frame = vfs_model.get_v_frame(payload)
            except:
                logger.warning("Cannot extract v-frame. Drop pkt!")
                return
            vf_index = vfs_model.compute_vf_index(len(v_frame), NODE_ID, seed)
            alloc_index, in_rand_frame = vfs_model.compute_alloc_index(
                vf_index, NODE_ID, v_frame, node_amount)

            stop_rx_ts = now_timestamp + 0.4
            # TODO: Duo to various delays, adjust a bit to before firing round up second
            next_tx_ts = begin_timestamp + (NODE_SLOT_TIME *
                                            alloc_index) - TRANSMIT_DELAY

            logger.info(
                "{} Node recv VFS_BROADCAST {}, BS time {}, Total {}, Seed {}, Delay {}, "
                "\nv-frame index: {}, alloc-index: {}, fall to rand-frame: {},"
                "\nv-frame: {}".format(
                    str(datetime.fromtimestamp(now_timestamp)), pktno,
                    str(datetime.fromtimestamp(pkt_timestamp)), node_amount,
                    seed, delta, vf_index, alloc_index, in_rand_frame,
                    v_frame))
            # logger.debug("begin {}, stop_rx_ts {}, next_tx_ts {}".format(
            #     str(datetime.fromtimestamp(begin_timestamp)), str(datetime.fromtimestamp(stop_rx_ts)),
            #     str(datetime.fromtimestamp(next_tx_ts))))
            return

    def fire_at_absolute_second():
        for i in range(10000):
            check_time = tx_tb.sink.get_time_now().get_real_secs()
            pivot_time = math.ceil(check_time)
            variance = pivot_time - check_time
            if -0.0002 < variance < 0.0002:
                logger.info("Fire at absolute {}".format(
                    str(datetime.fromtimestamp(check_time))))
                break
            time.sleep(0.0001)

    def usrp_sleep(interval_sec):
        wake_up_timestamp = tx_tb.sink.get_time_now().get_real_secs(
        ) + interval_sec
        for i in range(50000):
            now_timestamp = tx_tb.sink.get_time_now().get_real_secs()
            if now_timestamp >= wake_up_timestamp:
                break
            time.sleep(0.0001)

    def fire_at_expected_time(start_time):
        for i in range(50000):
            now_timestamp = tx_tb.sink.get_time_now().get_real_secs()
            if now_timestamp >= start_time:
                logger.info("Fire at {}".format(
                    str(datetime.fromtimestamp(now_timestamp))))
                return
            time.sleep(0.0001)
        logger.warning("ALERT!! not fire at {}".format(
            str(datetime.fromtimestamp(start_time))))

    def check_thread_is_done(max_pkt_amt):
        for i in range(10000):
            if not my_thread.is_alive() and my_iteration >= max_pkt_amt:
                now_ts = tx_tb.sink.get_time_now().get_real_secs()
                logger.debug("{} - thread done - ".format(
                    str(datetime.fromtimestamp(now_ts))))
                return
            time.sleep(0.0001)
        now_ts = tx_tb.sink.get_time_now().get_real_secs()
        logger.debug("ALERT!! thread timeout at {}".format(
            str(datetime.fromtimestamp(now_ts))))

    #######################################
    # main
    #######################################

    parser = OptionParser(option_class=eng_option, conflict_handler="resolve")
    expert_grp = parser.add_option_group("Expert")
    parser.add_option("-s",
                      "--size",
                      type="eng_float",
                      default=400,
                      help="set packet size [default=%default]")
    parser.add_option("-M",
                      "--megabytes",
                      type="eng_float",
                      default=1.0,
                      help="set megabytes to transmit [default=%default]")
    parser.add_option("",
                      "--discontinuous",
                      action="store_true",
                      default=False,
                      help="enable discontinuous mode")
    parser.add_option("",
                      "--from-file",
                      default=None,
                      help="use intput file for packet contents")
    parser.add_option("",
                      "--to-file",
                      default=None,
                      help="Output file for modulated samples")
    # Add unused log_file option to prevent 'no such option' error
    parser.add_option("", "--logfile", default=None)
    parser.add_option("", "--scheme", default=None)

    digital.ofdm_mod.add_options(parser, expert_grp)
    digital.ofdm_demod.add_options(parser, expert_grp)
    transmit_path.add_options(parser, expert_grp)
    receive_path.add_options(parser, expert_grp)
    uhd_transmitter.add_options(parser)
    uhd_receiver.add_options(parser)

    (options, args) = parser.parse_args()
    if len(args) != 0:
        logger.error("Parse error: {}\n".format(sys.stderr))
        sys.exit(1)
    logger.info("----------------------------------------------------------")
    logger.info("Input options: \n{}".format(str(options)))
    logger.info("----------------------------------------------------------\n")

    if options.rx_freq is None or options.tx_freq is None:
        logger.error("You must specify -f FREQ or --freq FREQ\n")
        sys.exit(1)
    if options.scheme is None:
        logger.error("You must specify --scheme SCHEME\n")
        sys.exit(1)
    options.scheme = options.scheme.upper()
    if options.scheme not in [str(e) for e in list(Scheme)]:
        logger.error("Not support scheme: {}\n".format(options.scheme))
        sys.exit(1)

    # Decide is BS or Node role
    IS_BS_ROLE = not bool(options.args)

    # build tx/rx tables
    tx_tb = TxTopBlock(options)
    if IS_BS_ROLE:
        rx_tb = RxTopBlock(rx_bs_callback, options)
    else:  # Node role
        rx_tb = RxTopBlock(rx_node_callback, options)

        # Use device serial number as Node ID
        NODE_ID = tx_tb.sink.get_usrp_mboard_serial()
        # Append to required length
        NODE_ID = NODE_ID.zfill(NODE_ID_LEN)
        assert len(
            NODE_ID) == NODE_ID_LEN, "USRP NODE_ID {} len must be {}".format(
                NODE_ID, NODE_ID_LEN)
        logger.info("\nNODE ID: {}".format(NODE_ID))

    logger.info("\nClock Rate: {} MHz".format(tx_tb.sink.get_clock_rate() /
                                              1000000))

    logger.info("\n####### Test Protocol: {} #######".format(options.scheme))

    if IS_BS_ROLE:
        logger.info("\nPresume known nodes: {}".format(TEST_NODE_LIST))

    # USRP device aligns with PC time (NTP)
    pc_now = time.time()
    tx_tb.sink.set_time_now(uhd.time_spec(pc_now))
    now_ts = tx_tb.sink.get_time_now().get_real_secs()
    logger.info("\n{} Adjust to PC time: {}\n".format(
        str(datetime.fromtimestamp(time.time())),
        str(datetime.fromtimestamp(now_ts))))
    # now_ts2 = rx_tb.source.get_time_now().get_real_secs()
    # sys_time = uhd.time_spec.get_system_time().get_real_secs()
    # logger.debug("\n{} Time alignment... Device txtime: {}, rxtime: {}, system time: {}\n".format(
    #              str(datetime.fromtimestamp(time.time())), str(datetime.fromtimestamp(get_time)),
    #              str(datetime.fromtimestamp(now_ts2)), str(datetime.fromtimestamp(sys_time))))

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

    pkt_size = int(options.size)
    tx_tb.start()
    rx_tb.start()

    for y in range(REPEAT_TEST_COUNT):

        logger.info(
            "\n\n============================================================================================="
        )
        logger.info(
            "========================================== ROUND {} =========================================="
            .format(y + 1))
        logger.info(
            "=============================================================================================\n\n"
        )

        ##################### SYNC : START #####################

        if IS_BS_ROLE:
            ################# BS #################
            _sync_start = tx_tb.sink.get_time_now().get_real_secs()

            sync_counts = 2
            for z in range(sync_counts):
                # Note: TX cannot be lock initially
                if z == 0 and y == 0:
                    rx_tb.lock()
                else:
                    tx_tb.unlock()

                logger.info("------ Broadcast Beacon ------")
                _start = tx_tb.sink.get_time_now().get_real_secs()
                # BS: Send beacon signals. Time precision thread
                do_every_beacon(0.005, send_beacon_pkt, tx_tb, pkt_size,
                                MAX_PKT_AMT)
                # Clocking thread
                check_thread_is_done(MAX_PKT_AMT)
                _end = rx_tb.source.get_time_now().get_real_secs()
                logger.info(" - duration {} -".format(_end - _start))
                logger.info("------ Broadcast Beacon end --------")
                tx_tb.lock()

                # sleep longer in last loop, finishing sync cycle
                sleep_sec = 0.5 if z == sync_counts - 1 else 0.2
                logger.info("Sleep for {} second\n".format(sleep_sec))
                usrp_sleep(sleep_sec)

            logger.info(" - Sync duration {} -\n".format(
                rx_tb.source.get_time_now().get_real_secs() - _sync_start))

            # # Deprecated. PROF TSENG: No need response-beacon, might cause collision
            # rx_tb.unlock()
            # logger.info("------ Listening ------")
            # next_tx_ts = 0  # reset next_tx
            # while next_tx_ts == 0 or next_tx_ts > now_ts:
            #     time.sleep(0.01)
            #     now_ts = rx_tb.source.get_time_now().get_real_secs()
            #     # logger.debug("now {} next {}".format(str(datetime.fromtimestamp(now_ts)), str(datetime.fromtimestamp(next_tx_ts))))
            # logger.info("------ Stop listen at {} ------".format(str(datetime.fromtimestamp(now_ts))))
            # rx_tb.lock()
            ################ BS end ##############

        else:
            ################ Node ################
            # Note: TX cannot be lock initially
            if y != 0:
                rx_tb.unlock()

            logger.info("------ Listening ------")
            stop_rx_ts = 0  # reset
            while stop_rx_ts == 0 or stop_rx_ts > now_ts:
                time.sleep(0.01)
                now_ts = rx_tb.source.get_time_now().get_real_secs()
                # logger.debug("now {} next {}".format(str(datetime.fromtimestamp(now_ts)), str(datetime.fromtimestamp(stop_rx_ts))))
            rx_tb.lock()
            logger.info("------ Stop listen at {} ------".format(
                str(datetime.fromtimestamp(now_ts))))

            # Deprecated. PROF TSENG: No need response-beacon, might cause collision
            # for z in range(2):
            #
            #     if z != 0:
            #         rx_tb.unlock()
            #     logger.info("------ Listening ------")
            #     next_tx_ts = 0  # reset next_tx
            #     while next_tx_ts == 0 or next_tx_ts > now_ts:
            #         time.sleep(0.01)
            #         now_ts = rx_tb.source.get_time_now().get_real_secs()
            #         # logger.debug("now {} next {}".format(str(datetime.fromtimestamp(now_ts)), str(datetime.fromtimestamp(next_tx_ts))))
            #     logger.info("------ Stop listen at {} ------".format(str(datetime.fromtimestamp(now_ts))))
            #     rx_tb.lock()
            #
            #     if z != 0:
            #         tx_tb.unlock()
            #     logger.info("------ Send Response Beacon ------")
            #     _start = tx_tb.sink.get_time_now().get_real_secs()
            #     # Node: Send response-beacon signals. Time precision thread
            #     do_every_beacon(0.005, send_resp_beacon_pkt, tx_tb, pkt_size, MAX_PKT_AMT)
            #     # Clocking thread
            #     check_thread_is_done(MAX_PKT_AMT)
            #     _end = rx_tb.source.get_time_now().get_real_secs()
            #     logger.info(" - duration {} -".format(_end - _start))
            #     logger.info("------ Send Response Beacon end ------")
            #     tx_tb.lock()
            ################ Node end ############

        ######################## SYNC : END #########################

        if options.scheme == Scheme.PS.key:
            ################### Perfect Scheme: START ###################

            if IS_BS_ROLE:
                ################# BS #################
                # Deprecated
                # nodes_sync_delta.update({NODE_ID_A: [1, 2, 3],
                #                          NODE_ID_B: [4, 5, 6],
                #                          '0000000003': [7, 8, 9],
                #                          '0000000004': [10, 11, 12],
                #                          '0000000005': [13, 14, 15]})
                # node_amount = len(nodes_sync_delta)

                # rx_tb.lock()

                # Mark Frame T start time
                _ps_start = tx_tb.sink.get_time_now().get_real_secs()

                # calculate perfect seed
                _start = tx_tb.sink.get_time_now().get_real_secs()
                ps_model.generate_perfect_seed(TEST_NODE_LIST)
                _end = rx_tb.source.get_time_now().get_real_secs()
                logger.info(" - duration {} -".format(_end - _start))

                tx_tb.unlock()
                logger.info("------ Broadcast PS packets ------")
                # To ensure broadcast end within a full second, adjust to start at absolute second
                fire_at_absolute_second()

                _start = tx_tb.sink.get_time_now().get_real_secs()
                do_every_protocol_bs(0.005, ps_model.broadcast_ps_pkt, tx_tb,
                                     pkt_size, len(TEST_NODE_LIST),
                                     MAX_PKT_AMT)
                # Clocking thread
                check_thread_is_done(MAX_PKT_AMT)
                _end = rx_tb.source.get_time_now().get_real_secs()
                logger.info(" - duration {} -".format(_end - _start))
                logger.info("------ Broadcast PS end ------")
                tx_tb.lock()

                rx_tb.unlock()
                logger.info("------ Listen PS packets start ------")
                listen_only_to = [PacketType.PS_PKT.index]
                _start = tx_tb.sink.get_time_now().get_real_secs()
                # Listen end time is after last node transmission ended. Add some misc delay
                stop_rx_ts = ps_model.nodes_expect_time[-1][-1] + 0.5
                while stop_rx_ts == 0 or stop_rx_ts > now_ts:
                    time.sleep(0.01)
                    now_ts = rx_tb.source.get_time_now().get_real_secs()
                    # logger.debug("now {} next {}".format(str(datetime.fromtimestamp(now_ts)), str(datetime.fromtimestamp(next_tx_ts))))
                _end = rx_tb.source.get_time_now().get_real_secs()
                logger.info(" - duration {} -".format(_end - _start))
                logger.info("------ Listen PS packets end ------")
                listen_only_to = []
                rx_tb.lock()

                now_ts = rx_tb.source.get_time_now().get_real_secs()
                logger.info("\n - PS duration {} -".format(now_ts - _ps_start))
                logger.info("------ PS cycle ends at {} ------\n".format(
                    str(datetime.fromtimestamp(now_ts))))

                # logger.info("Sleep for 0.2 second")
                # usrp_sleep(0.2)
                ################ BS end ##############

            else:
                ################ Node ################
                rx_tb.unlock()
                logger.info("------ Listening PS broadcast ------")
                listen_only_to = [PacketType.PS_BROADCAST.index]
                stop_rx_ts = 0  # reset
                while stop_rx_ts == 0 or stop_rx_ts > now_ts:
                    time.sleep(0.01)
                    now_ts = rx_tb.source.get_time_now().get_real_secs()
                    # logger.debug("now {} next {}".format(str(datetime.fromtimestamp(now_ts)), str(datetime.fromtimestamp(stop_rx_ts))))
                logger.info(
                    "------ Stop listen PS broadcast at {} ------".format(
                        str(datetime.fromtimestamp(now_ts))))
                listen_only_to = []
                rx_tb.lock()

                # TODO: Adjust to node alloc period
                assert alloc_index != -1, "alloc_index is -1"

                logger.info("------ Ready to send PS packets ------")
                if y != 0:
                    tx_tb.unlock()

                fire_at_expected_time(next_tx_ts + COMMAND_DELAY)

                _start = tx_tb.sink.get_time_now().get_real_secs()
                ps_data = "Hello, I am node {}".format(NODE_ID)
                do_every_protocol_node(0.005, ps_model.send_ps_pkt, NODE_ID,
                                       tx_tb, pkt_size, ps_data,
                                       MAX_PKT_AMT_FOR_NODE)
                # Clocking thread
                check_thread_is_done(MAX_PKT_AMT_FOR_NODE)
                _end = rx_tb.source.get_time_now().get_real_secs()
                logger.info(" - duration {} -".format(_end - _start))
                logger.info("------ Send PS packets end ------")
                tx_tb.lock()

                # Node wait until PS cycle is over
                now_ts = rx_tb.source.get_time_now().get_real_secs()
                usrp_sleep(ps_end_ts - now_ts + COMMAND_DELAY)

                now_ts = rx_tb.source.get_time_now().get_real_secs()
                logger.info("\n------ PS cycle ends at {} ------\n".format(
                    str(datetime.fromtimestamp(now_ts))))
                ################ Node end ############

            ##################### Perfect Scheme: END #####################

        elif options.scheme == Scheme.VFS.key:
            ################### Virtual Frame Scheme: START ###################

            if IS_BS_ROLE:
                ################# BS #################
                # Deprecated
                # nodes_sync_delta.update({NODE_ID_A: [1, 2, 3],
                #                          NODE_ID_B: [4, 5, 6],
                #                          '0000000003': [7, 8, 9],
                #                          '0000000004': [10, 11, 12],
                #                          '0000000005': [13, 14, 15]})
                # node_amount = len(nodes_sync_delta)

                # rx_tb.lock()

                # Mark Frame T start time & expected end time
                vfs_start_ts = tx_tb.sink.get_time_now().get_real_secs()
                vfs_end_ts = vfs_start_ts + FRAME_TIME_T - 0.01  # give a bit deplay for ending

                # calculate VFS seed, v-frame & rand-frame
                _start = tx_tb.sink.get_time_now().get_real_secs()
                vfs_model.generate_seed_v_frame_rand_frame(TEST_NODE_LIST)
                _end = rx_tb.source.get_time_now().get_real_secs()
                logger.info(" - duration {} -".format(_end - _start))

                tx_tb.unlock()
                logger.info("------ Broadcast VFS packets ------")
                # To ensure broadcast end within a full second, adjust to start at absolute second
                fire_at_absolute_second()

                _start = tx_tb.sink.get_time_now().get_real_secs()
                do_every_protocol_bs(0.005, vfs_model.broadcast_vfs_pkt, tx_tb,
                                     pkt_size, len(TEST_NODE_LIST),
                                     MAX_PKT_AMT)
                # Clocking thread
                check_thread_is_done(MAX_PKT_AMT)
                _end = rx_tb.source.get_time_now().get_real_secs()
                logger.info(" - duration {} -".format(_end - _start))
                logger.info("------ Broadcast VFS end ------")
                tx_tb.lock()

                rx_tb.unlock()
                logger.info("------ Listen VFS packets start ------")
                listen_only_to = [PacketType.VFS_PKT.index]
                _start = tx_tb.sink.get_time_now().get_real_secs()
                # Listen end time is after last node transmission ended, or till frame T ended.
                stop_rx_ts = vfs_model.nodes_expect_time[-1][
                    -1] + 0.5  # Add misc delay
                while stop_rx_ts == 0 or stop_rx_ts > now_ts or vfs_end_ts > now_ts:
                    time.sleep(0.01)
                    now_ts = rx_tb.source.get_time_now().get_real_secs()
                    # logger.debug("now {} next {}".format(str(datetime.fromtimestamp(now_ts)), str(datetime.fromtimestamp(next_tx_ts))))
                _end = rx_tb.source.get_time_now().get_real_secs()
                logger.info(" - duration {} -".format(_end - _start))
                logger.info("------ Listen VFS packets end ------")
                listen_only_to = []
                rx_tb.lock()

                now_ts = rx_tb.source.get_time_now().get_real_secs()
                logger.info("\n - VFS duration {} -".format(now_ts -
                                                            vfs_start_ts))
                logger.info("------ VFS cycle ends at {} ------\n".format(
                    str(datetime.fromtimestamp(now_ts))))

                # logger.info("Sleep for 0.2 second")
                # usrp_sleep(0.2)
                ################# BS end #############

            else:
                ################ Node ################
                # Mark Frame T start time & expected end time
                vfs_start_ts = tx_tb.sink.get_time_now().get_real_secs()
                vfs_end_ts = vfs_start_ts + FRAME_TIME_T - 0.01  # give a bit deplay for ending

                rx_tb.unlock()
                logger.info("------ Listening VFS broadcast ------")
                listen_only_to = [PacketType.VFS_BROADCAST.index]
                stop_rx_ts = 0  # reset
                while stop_rx_ts == 0 or stop_rx_ts > now_ts:
                    time.sleep(0.01)
                    now_ts = rx_tb.source.get_time_now().get_real_secs()
                    # logger.debug("now {} next {}".format(str(datetime.fromtimestamp(now_ts)), str(datetime.fromtimestamp(stop_rx_ts))))
                logger.info(
                    "------ Stop listen VFS broadcast at {} ------".format(
                        str(datetime.fromtimestamp(now_ts))))
                listen_only_to = []
                rx_tb.lock()

                # TODO: Adjust to node alloc period
                if alloc_index == -1:
                    logger.warning(
                        "WARNING: alloc_index is -1, cannot join this session. Skip..."
                    )
                    time.sleep(7)
                    continue
                # assert alloc_index != -1, "alloc_index is -1"

                logger.info("------ Ready to send VFS packets ------")
                if y != 0:
                    tx_tb.unlock()

                fire_at_expected_time(next_tx_ts + COMMAND_DELAY)

                _start = tx_tb.sink.get_time_now().get_real_secs()
                vfs_data = "Hello, I am node {}".format(NODE_ID)
                do_every_protocol_node(0.005, vfs_model.send_vfs_pkt, NODE_ID,
                                       tx_tb, pkt_size, vfs_data,
                                       MAX_PKT_AMT_FOR_NODE)
                # Clocking thread
                check_thread_is_done(MAX_PKT_AMT_FOR_NODE)
                _end = rx_tb.source.get_time_now().get_real_secs()
                logger.info(" - duration {} -".format(_end - _start))
                logger.info("------ Send VFS packets end ------")
                tx_tb.lock()

                # Node wait until VFS cycle is over
                now_ts = rx_tb.source.get_time_now().get_real_secs()
                usrp_sleep(vfs_end_ts - now_ts + COMMAND_DELAY)

                now_ts = rx_tb.source.get_time_now().get_real_secs()
                logger.info("\n - VFS duration {} -".format(now_ts -
                                                            vfs_start_ts))
                logger.info("------ VFS cycle ends at {} ------\n".format(
                    str(datetime.fromtimestamp(now_ts))))
                ################ Node end ############

            ##################### Virtual Frame Scheme: END #####################

    #tx_tb.unlock()
    #tx_tb.wait()
    #rx_tb.unlock()
    #rx_tb.wait()
    tx_tb.stop()
    rx_tb.stop()

    logger.info(
        "\n\n============================================================================================="
    )
    logger.info(
        "========================================= TEST END =========================================="
    )
    logger.info(
        "=============================================================================================\n\n"
    )

    sys.exit(0)
Example #35
0
def main():

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

    def send_pkt(payload='', eof=False):
        return tb.txpath.send_pkt(payload, eof)

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

    parser.add_option("","--to-file", default=None,
                      help="Output file for modulated samples")
    parser.add_option("-s", "--size", type="eng_float", default=400,
                      help="set packet size [default=%default]")
    parser.add_option("-M", "--megabytes", type="eng_float", default=1.0,
                      help="set megabytes to transmit [default=%default]")


#rcv
    receive_path.add_options(parser, expert_grp)
    uhd_receiver.add_options(parser)
    digital.ofdm_demod.add_options(parser, expert_grp)
#trans
    transmit_path.add_options(parser, expert_grp)
    digital.ofdm_mod.add_options(parser, expert_grp)
    uhd_transmitter.add_options(parser)

    (options, args) = parser.parse_args ()

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

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

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

    tb.start()                      # start flow graph
#trans
    nbytes = int(1e3 * options.megabytes)
    n = 0
    pktno = 0
    pkt_size = int(options.size)

    if 1:
        while n < nbytes:
            if options.from_file is None:
                #data = (pkt_size - 2) * (pktno & 0xff) 
                data = 'hellognuradio' 
            else:
                data = source_file.read(pkt_size - 2)
                if data == '':
                    break;

            payload = struct.pack('!H', pktno & 0xffff) + data
        
            send_pkt(payload)
            n += len(payload)
            print 'transmitting pktno = ', pktno
            pktno += 1
            
    send_pkt(eof=True)
    last_rcv_time = time.clock()
    while 1:
        while len(rcv_buffer) > 0:
            (pktno, payload) = rcv_buffer.pop(0)
            print 'pktno = ', pktno, 'payload = ', payload[2:]
        now = time.clock()
        #if not sleep, it seems it will chew up all CPU!
        time.sleep(0.3)
        if (now - last_rcv_time > 2):
           break
    print '########################TEST tx_rx_self FINISHED################################'
    print '########################NOW BEGIN TESTING carrier sense##########################'
    tb.rxpath.set_carrier_threshold(2)
    print 'threshold = ', tb.rxpath.carrier_threshold()
    while 1:
        print 'carrier sense : ', tb.rxpath.carrier_sensed()
        time.sleep(0.1)
    tb.wait()                       # wait for it to finish
Example #36
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
Example #37
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()
Example #38
0
def main():
    global n_rcvd, n_right,flag
    
    packets_delivered = []
    not_delivered = True    

    flag = 0

    n_rcvd = 0
    n_right = 0
    
    def rx_callback(ok, payload):
        global n_rcvd, n_right, flag

        (pktno,) = struct.unpack('!H', payload[0:2])
	data = payload[2:]
	#Check if packet is not a sensing packet and if so, send it to sock
	#Also check if the packet has already been delivered
	if pktno <= 1000:
        	
        	n_rcvd += 1
		if ok:
            		n_right += 1
			for i in range(0, len(packets_delivered)):
				if packets_delivered[i] == pktno:
					not_delivered = False
            		if options.server and not_delivered:
				packets_delivered.append(pktno)
                		sock.sendall(data)
			not_delivered = True
	#Check if pakcet is a sensing packet and jump freq accordingly
        if pktno > 1000 and flag == 0:
		if ok :
            		flag = 1
	    		new_freq =int(float(data))
	    		new = new_freq/1.0
	    		print "About to change freq"
	    		#Sleep to keep sync
	    		time.sleep(0.5)            

            		options.rx_freq = new
            		source = uhd_receiver(options.args, symbol_rate2,
                                       options.samples_per_symbol, options.rx_freq, 
                                       options.lo_offset, options.rx_gain,
                                       options.spec, options.antenna,
                                       options.clock_source, options.verbose)
            		rxpath = receive_path(demodulator2, rx_callback, options)
        #Reset flag if sensing packet burst is over
	if pktno <1000 and flag == 1:
		flag = 0
        
        print "ok = %5s  pktno = %4d  n_rcvd = %4d  n_right = %4d frequency = %s" % (
            ok, pktno, n_rcvd, n_right, options.rx_freq)

    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='qpsk',
                      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."
    
    time.sleep(9.5)
    tb.start()        # start flow graph
    tb.wait()         # wait for it to finish

    if options.server:
    	sock.close()
Example #39
0
def main():
    global n_rcvd, n_right, nopkt, start

    random.seed(os.urandom(100))

    n_rcvd = 0
    n_right = 0
    nopkt = 1

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

        if ok:
            nopkt = 0
            n_right += 1
            if options.server:
                sock.sendall(data)


#                if n_right == 1000:
#					print "JSHABJKWHBEWJQKBEHWQKJWQEJWQRKBKJWQRBOJWRQB\n"
#					sock.close()
        start = time.time()
        #print "ok = %5s  pktno = %4d  n_rcvd = %4d  n_right = %4d" % (
        #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='gmsk',
                      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', 51001)
        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
    #    tb.wait()         # wait for it to finish

    freq_list = [
        options.rx_freq, options.rx_freq + 1000000.0,
        options.rx_freq - 1000000.0
    ]
    i = 0
    nopkt = 1
    while 1:
        #		pwr= tb.rxpath.probe.level()
        while (nopkt):
            tb.source.set_freq(freq_list[i % 3], 0)
            i += 1
            time.sleep(0.05)

        if (time.time() - start > 0.5):
            nopkt = 1

    if options.server:
        sock.close()
Example #40
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
Example #41
0
def main():
    global n_rcvd, n_right, start_time, stop_rcv

    TIMEOUT = 600 # 600 sec for hurdle 3
    n_rcvd = 0
    n_right = 0
    lock = Lock()
    start_time = 0
    mstr_cnt = 0
    stop_rcv = 0



    TCP_IP='idb2'
    TCP_PORT=5102
    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, channel):
        global n_rcvd, n_right, start_time, stop_rcv
        try:
	        (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  channel = %1d" %(
	            ok, pktno, n_rcvd, n_right, channel)
        except:
	        return

    def rx_callback0(ok, payload):
		lock.acquire()
		rx_callback(ok, payload, 0)
		lock.release()

    def rx_callback1(ok, payload):
       lock.acquire()
       rx_callback(ok, payload, 1)
       lock.release()

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

    custom_grp = parser.add_option_group("Custom")
    custom_grp.add_option("","--guard-width", type="eng_float", default=250e3,
                      help="guard region width")
    custom_grp.add_option("","--band-trans-width", type="eng_float", default=50e3,
                      help="transition width for band pass filter")
    custom_grp.add_option("","--low-trans-width", type="eng_float", default=50e3,
                      help="transition width for low pass filter")
    custom_grp.add_option("","--file-samp-rate", type="eng_float", default=1e6,
                      help="file sample rate")
    custom_grp.add_option("","--rs-n", type="int", default=252,
                      help="reed solomon n")
    custom_grp.add_option("","--rs-k", type="int", default=241,
                      help="reed solomon k")
    custom_grp.add_option("","--num-taps", type="int", default=2,
                      help="taps")

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

    options.bitrate = 3000e3
    options.rx_gain = 50
    options.constellation_points = 16

    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_callback0, rx_callback1, 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 h3_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

    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()
Example #42
0
def main():
    def send_pkt(payload='', eof=False):
        return tb.txpath.send_pkt(payload, eof)

    global n_rcvd, n_right

    n_rcvd = 0
    n_right = 0

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

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

            print printable
            print "\n"

    parser = OptionParser(option_class=eng_option, conflict_handler="resolve")
    expert_grp = parser.add_option_group("Expert")
    parser.add_option("",
                      "--discontinuous",
                      action="store_true",
                      default=False,
                      help="enable discontinuous")
    parser.add_option("",
                      "--from-file",
                      default=None,
                      help="input file of samples to demod")
    parser.add_option("-M",
                      "--megabytes",
                      type="eng_float",
                      default=1.0,
                      help="set megabytes to transmit [default=%default]")
    parser.add_option("-s",
                      "--size",
                      type="eng_float",
                      default=400,
                      help="set packet size [default=%default]")
    parser.add_option("-p",
                      "--packno",
                      type="eng_float",
                      default=0,
                      help="set packet number [default=%default]")

    transmit_path.add_options(parser, expert_grp)
    digital.ofdm_mod.add_options(parser, expert_grp)
    uhd_transmitter.add_options(parser)

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

    (options, args) = parser.parse_args()

    if options.from_file is None:
        if options.rx_freq is None:
            sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
            parser.print_help(sys.stderr)
            sys.exit(1)
    if options.packno is not None:
        packno_delta = options.packno
        print "assign pktno start: %d" % packno_delta

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

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

    tb.start()  # start flow graph
    # generate and send packets
    nbytes = int(1e6 * options.megabytes)
    n = 0
    pktno = 0
    pkt_size = int(options.size)

    while n < nbytes:
        if options.from_file is None:
            data = (pkt_size - 2) * chr(pktno & 0xff)
        else:
            data = source_file.read(pkt_size - 2)
            if data == '':
                break

        payload = struct.pack('!H',
                              (pktno + int(packno_delta)) & 0xffff) + data
        send_pkt(payload)
        n += len(payload)
        sys.stderr.write('.')
        if options.discontinuous and pktno % 5 == 4:
            time.sleep(1)
        pktno += 1

    send_pkt(eof=True)
    time.sleep(2)  # allow time for queued packets to be sent
    tb.wait()  # wait for it to finish
Example #43
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
Example #44
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,file_input,\
           file_output, data, data_num, upload_file
    node_rx_q = Queue.Queue(maxsize=NODE_RX_MAX)
    node_rx_sem = threading.Semaphore(NODE_RX_MAX)  #up to the queue size
    thread_run = True
    alloc_index = -1
    last_node_amount = -1

    last_in_noaction = True
    data = "**heLLo**"  # default data str
    data_num = 0
    upload_file = True

    for i in range(NODE_RX_MAX):  # make all semaphore in 0 status
        node_rx_sem.acquire()

    def send_pkt(payload='', eof=False):
        return tb.txpath.send_pkt(payload, eof)

    global n_rcvd, n_right

    n_rcvd = 0
    n_right = 0

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

        # Filter out incorrect pkt
        if ok:

            thingy = decode_common_pkt_header(tb, payload)
            if not thingy:
                return
            (pktno, pkt_timestamp, pkt_type) = thingy

            n_right += 1
            now_ts = tb.sink.get_time_now().get_real_secs()
            node_rx_q.put(payload)
        else:
            logger.warning("Packet fail. Drop pkt!")

        return

    parser = OptionParser(option_class=eng_option, conflict_handler="resolve")
    expert_grp = parser.add_option_group("Expert")
    #    parser.add_option("","--discontinuous", action="store_true", default=False,
    #                      help="enable discontinuous")
    parser.add_option("",
                      "--from-file",
                      default=None,
                      help="input file of samples")
    #    parser.add_option("-M", "--megabytes", type="eng_float", default=1.0,
    #                      help="set megabytes to transmit [default=%default]")
    parser.add_option("-s",
                      "--size",
                      type="eng_float",
                      default=400,
                      help="set packet size [default=%default]")
    parser.add_option("-p",
                      "--packno",
                      type="eng_float",
                      default=0,
                      help="set packet number [default=%default]")
    parser.add_option("",
                      "--to-file",
                      default=None,
                      help="Output file for modulated samples")
    parser.add_option("", "--bs", default=None, help="assign if bs")

    transmit_path.add_options(parser, expert_grp)
    digital.ofdm_mod.add_options(parser, expert_grp)
    uhd_transmitter.add_options(parser)

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

    (options, args) = parser.parse_args()

    # Decide is BS or Node role
    IS_BS_ROLE = bool(options.bs)

    if options.from_file is None:
        if options.rx_freq is None:
            sys.stderr.write("You must specify -f FREQ or --freq FREQ\n")
            parser.print_help(sys.stderr)
            sys.exit(1)
    if options.packno is not None:
        packno_delta = options.packno
        logger.info("assign pktno start: %d" % packno_delta)

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

    # USRP device aligns with PC time (NTP)
    pc_now = time.time()
    tb.sink.set_time_now(uhd.time_spec(pc_now))
    tb.source.set_time_now(uhd.time_spec(pc_now))
    now_ts = tb.sink.get_time_now().get_real_secs()
    logger.info("\n{} Adjust to PC time: {}\n".format(
        str(datetime.fromtimestamp(time.time())),
        str(datetime.fromtimestamp(now_ts))))

    # get this node id
    NODE_ID = tb.sink.get_usrp_mboard_serial()
    # Append to required length
    NODE_ID = NODE_ID.zfill(NODE_ID_LEN)
    assert len(
        NODE_ID) == NODE_ID_LEN, "USRP NODE_ID {} len must be {}".format(
            NODE_ID, NODE_ID_LEN)
    logger.info("\nNODE ID: {}".format(NODE_ID))

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

    # node, open input file if assigned
    if not IS_BS_ROLE and (options.from_file is not None):
        try:
            file_input = open(options.from_file, "r")
            data = file_input.read(3)
            upload_file = True
            logger.info("Input file opened successfully")
        except:
            logger.error("Error: file not exist")
    elif not IS_BS_ROLE:
        upload_file = False
        data = str(data_num)
    else:
        pass

    # bs, open output file if assigned
    if IS_BS_ROLE and (options.to_file is not None):
        try:
            file_output = open(options.to_file, "w+",
                               buffering=0)  #no buffering, flush rightaway
            logger.info("Output file opened successfully")
        except:
            logger.error("Error: file not exist")

    tb.start()  # start flow graph

    n = 0
    pktno = 0
    pkt_size = int(options.size)

    def threadjob(pktno, IS_BS, NODE_ID):
        global thread_run, data, data_num, TEST_NODE_RETRY, TEST_NODE_LIST, i_care_ack, last_pktno
        logger.info("Please start host now...")
        boot_time = time.time()
        bs_start_time = 0
        nd_start_time = 0
        nd_in_response = False
        not_my_business = False
        time_data_collecting = len(TEST_NODE_LIST) * NODE_SLOT_TIME
        time_wait_for_my_slot = 0
        TEST_NODE_RETRY[:] = list(TEST_NODE_RETRY_DEFAULT)
        TEST_NODE_LIST = list(TEST_NODE_LIST_DEFAULT)
        last_data = -1

        i_care_ack = False

        last_pktno = -1

        print(TEST_NODE_LIST)
        print(TEST_NODE_LIST_DEFAULT)

        while thread_run:
            if IS_BS:
                if time.time() > (bs_start_time + time_data_collecting +
                                  TRANSMIT_DELAY):
                    #statstic
                    if pktno != 0:
                        for iid in TEST_NODE_RETRY:
                            logger.info("111111111111111111111111111")
                            logger.info("1 Data Timeout:{} 1".format(iid))
                            logger.info("111111111111111111111111111")
                            statistics[iid]['Missing'] += 1

                        temp = 0
                        for iid in TEST_NODE_RETRY_DEFAULT:
                            if iid in TEST_NODE_LIST:
                                temp = vfs_model.query_vack(iid)
                                if 1 == temp:
                                    statistics[iid]['ACK'] += 1
                                elif 2 == temp:
                                    statistics[iid]['NAK'] += 1
                                else:
                                    pass
                        print(statistics)

                    print("\n......Frame start......")
                    #prepare
                    if pktno != 0:
                        i = 0

                        TEST_NODE_LIST[:] = []

                        #prepare - scheduling
                        for iid in TEST_NODE_LIST_DEFAULT:
                            # join this run, for all scheduled or retry devices
                            if pktno % TEST_NODE_SCHEDULE[i] == 0:
                                TEST_NODE_LIST.append(iid)
                                logger.info("scheduled:{}".format(iid))
                                #statstic
                                if iid in statistics:
                                    statistics[iid]['Schedule'] += 1
                            elif iid in TEST_NODE_RETRY:
                                TEST_NODE_LIST.append(iid)
                                logger.info("retry:{}".format(iid))
                                #statstic
                                if iid in statistics:
                                    statistics[iid]['Retry'] += 1
                            else:
                                pass
                                #TEST_NODE_LIST.append("000000000{}".format(i+1))

                            i = i + 1
                        TEST_NODE_RETRY[:] = []
                        for iid in TEST_NODE_RETRY_DEFAULT:
                            if iid in TEST_NODE_LIST:
                                TEST_NODE_RETRY.append(iid)
                    else:
                        #statstic
                        for iid in statistics:
                            statistics[iid]['Schedule'] += 1

                    vfs_model.generate_seed_v_frame_rand_frame2(
                        TEST_NODE_LIST_DEFAULT, TEST_NODE_LIST)

                    #statstic
                    if '00030757AF' in vfs_model.rand_frame and '00030757AF' in TEST_NODE_LIST:
                        statistics['00030757AF']['Rand'] += 1
                    if '000307B24B' in vfs_model.rand_frame and '000307B24B' in TEST_NODE_LIST:
                        statistics['000307B24B']['Rand'] += 1

                    #send boardcast
                    vfs_model.send_dummy_pkt(
                        tb)  # hacking, send dummy pkt to avoid data lost
                    vfs_model.broadcast_vfs_pkt(tb, pkt_size,
                                                len(TEST_NODE_LIST),
                                                pktno + int(packno_delta))

                    pktno += 1

                    #statistic
                    statistics['00030757AF']['Bcast'] = pktno
                    statistics['000307B24B']['Bcast'] = pktno

                    bs_start_time = time.time()

                else:
                    pass
                    #vfs_model.send_dummy_pkt(tb)

            else:  #node
                if nd_in_response and time.time() > (nd_start_time +
                                                     time_wait_for_my_slot):
                    if not_my_business:  #this run is not my run
                        pass
                    else:
                        logger.info("data on hand {}".format(data))
                        #prepare data
                        if upload_file:
                            try:
                                file_input.seek(3 * data_num)
                                data = file_input.read(3)
                                if data == '':
                                    thread_run = False
                                    tb.txpath.send_pkt(eof=True)
                                    tb.stop()
                                    break

                                logger.info(
                                    "read current data {}".format(data))

                            except:
                                #error end
                                thread_run = False
                                tb.txpath.send_pkt(eof=True)
                        else:
                            data = str(data_num)
                            if data == str(TEST_DATA_MAX + 1):
                                thread_run = False
                                tb.txpath.send_pkt(eof=True)
                                tb.stop()
                                break
                            logger.info("read current data {}".format(data))

                        vfs_model.send_dummy_pkt(
                            tb)  # hacking, send dummy pkt to avoid data lost
                        vfs_model.send_vfs_pkt(NODE_ID, tb, pkt_size, data,
                                               data_num, pktno)
                        i_care_ack = True

                        logger.info(
                            "\n===========================\npktno:{}\ndata numer:{}\ndata:{}\nstatistics:{}\n==========================="
                            .format(pktno, data_num, data,
                                    statistics_dev[NODE_ID]))

                        pktno += 1
                        nd_in_response = False
                        not_my_business = False

                else:
                    #print "nd_in_response{}, time {} > {} ".format(nd_in_response,time.time(), (nd_start_time + time_wait_for_my_slot))
                    pass
                    #vfs_model.send_dummy_pkt(tb)
                    #tb.txpath.send_pkt(eof=True)

            #while node_rx_sem.acquire(False):
            if not node_rx_q.empty():
                payload = node_rx_q.get()
                if payload:
                    #here we need to decode the payload first
                    if IS_BS:
                        thingy = action(tb, vfs_model, payload, NODE_ID)
                        if thingy:
                            (delta, node_id, node_pktno, upload_data,
                             data_number) = thingy
                            #check the data number in payload

                            if vfs_model.check_data_num(node_id, data_number):
                                logger.info("data:{} length:{}".format(
                                    upload_data, len(upload_data)))
                                vfs_model.set_data_num(
                                    node_id, data_number + 1
                                    & 0xffff)  #keep track in vfs module
                                try:
                                    #file_output.write(upload_data)
                                    writefile(node_id, upload_data)
                                except:
                                    logger.info("write file fail")

                                if upload_data == str(TEST_DATA_MAX):
                                    logger.info("=====test end=====")
                                    thread_run = False
                                    tb.txpath.send_pkt(eof=True)
                                    tb.stop()
                                    break
                                if int(upload_data) != (last_data + 1):
                                    logger.info(
                                        "=====Error protocol fail=====upload{},check{}"
                                        .format(upload_data, last_data + 1))
                                    thread_run = False
                                    tb.txpath.send_pkt(eof=True)
                                    tb.stop()
                                    break
                                last_data = last_data + 1

                                TEST_NODE_RETRY.remove(node_id)

                            else:
                                logger.info("2222222222222222")
                                logger.info("2 SEQ mismatch 2")
                                logger.info("2222222222222222")
                                statistics[node_id]['SEQ'] += 1
                                TEST_NODE_RETRY.remove(node_id)
                        else:
                            logger.critical("[Decode Error] payload fail")
                            logger.info("3333333333333333")
                            logger.info("3 Payload Error3")
                            logger.info("3333333333333333")
                            statistics['00030757AF']['Decode'] += 1
                            statistics['000307B24B']['Decode'] += 1
                    else:
                        logger.info("\n... get broadcast ...")

                        statistics_dev[NODE_ID]['GotBcast'] += 1
                        thingy = action(tb, vfs_model, payload, NODE_ID)

                        if thingy:
                            if "not-my-business" == thingy:
                                #not schedule in this run

                                nd_in_response = True
                                not_my_business = True
                            else:  #success and check
                                (node_amount, seed, delta, vf_index,
                                 alloc_index, in_rand_frame, v_frame) = thingy
                                time_wait_for_my_slot = alloc_index * NODE_SLOT_TIME
                                nd_start_time = time.time()
                                nd_in_response = True
                                if in_rand_frame:
                                    logger.info("666666666666666666666666666")
                                    logger.info("6  Rand Frame - SKIP      6")
                                    logger.info("666666666666666666666666666")
                                    statistics_dev[NODE_ID]['RAND'] += 1
                                    not_my_business = True

                                elif alloc_index < 0:
                                    logger.info("555555555555555555555555555")
                                    logger.info("5         No Action       5")
                                    logger.info("555555555555555555555555555")
                                    not_my_business = True

                                    statistics_dev[NODE_ID]['NoAction'] += 1
                                else:
                                    logger.info(
                                        "I will upload at slot {}, wait for {}s"
                                        .format(alloc_index,
                                                time_wait_for_my_slot))
                                    not_my_business = False

                                    statistics_dev[NODE_ID]['askup'] += 1
                                #vfs_model.send_vfs_pkt( NODE_ID, tb, pkt_size, "**heLLo**{}".pktno, pktno)
                        else:
                            logger.warn("error during decode VFS_BROADCAST")
                            logger.info("777777777777777777777777777")
                            logger.info("7         Decode          7")
                            logger.info("777777777777777777777777777")
                            statistics_dev[NODE_ID]['Decode'] += 1

        print "... thread out ..."
        #node_rx_sem.release

    thread = threading.Thread(target=threadjob,
                              args=(pktno, IS_BS_ROLE, NODE_ID))
    thread.daemon = True  #make it a daemon thread
    thread_run = True
    thread.start()

    time.sleep(2)  # allow time for queued packets to be sent
    tb.wait()  # wait for it to finish
    thread_run = False
    while thread.isAlive():
        time.sleep(1)

    try:
        file_input.close()
    except:
        pass
    try:
        file_output.close()
    except:
        pass
    print "join done"
Example #45
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
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()
Example #47
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
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
Example #49
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
Example #50
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"
Example #51
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()
Example #52
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)
Example #53
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()
Example #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)
Example #55
0
def main():


    global n_rcvd, n_right, header, pktno
    header , pktno  = None, None
    n_rcvd = 0
    n_right = 0


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

        if options.type=='Rx':
            print "Tx = %s  ok = %5s  pktno = %4d  n_rcvd = %4d  n_right = %4d" % (header,
            ok, pktno, n_rcvd, n_right)

    demods = digital.modulation_utils.type_1_demods()

    usage = "usage: %prog [options]"
    parser = OptionParser(option_class=eng_option, usage=usage, conflict_handler="resolve")
    expert_grp = parser.add_option_group("Expert")
    #usrp_options.add_rx_options(parser)

    ### Periodogram parameters ###
    parser.add_option("-d", "--decim", type="intx", default=400,
            help="set decimation to DECIM [default=%default]")
    parser.add_option("-F", "--fft-size", type="int", default=128,
            help="Specify number of FFT bins [default=%default]")
    parser.add_option("-b", "--noofbins", type="int", default=128,
                help="Specify number of bins to consider [default=%default]")
    parser.add_option("-N", "--nblocks", type="int", default=250,
            help="Specify size of Nblocks [default=%default]")
    ### For USRP2 and UHD ###
    parser.add_option("--scalarx", type="int", default=1000,
            help="Specify the scalar multiplier for USRP2 [default=%default]")

    parser.add_option("-a", "--args", type="string", default="",
                  help="UHD device address args [default=%default]")
    parser.add_option("", "--spec", type="string", default=None,
                  help="Subdevice of UHD device where appropriate")
    parser.add_option("-A", "--antenna", type="string", default=None,
                  help="select Rx Antenna where appropriate")
    parser.add_option("", "--rx-freq", type="eng_float", default=None,
                  help="set receive frequency to FREQ [default=%default]",
                  metavar="FREQ")
    parser.add_option("", "--lo-offset", type="eng_float", default=0,
                  help="set local oscillator offset in Hz (default is 0)")
    parser.add_option("", "--rx-gain", type="eng_float", default=None,
                  help="set receive gain in dB (default is midpoint)")
    parser.add_option("-C", "--clock-source", type="string", default=None,
                  help="select clock source (e.g. 'external') [default=%default]")
    ### You tell me what this is ###
    parser.add_option("--real-time", action="store_true", default=False,
            help="Attempt to enable real-time scheduling")

    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("-t", "--type", type="string", default="Rx/S",
                  help="Select mode - Rx,S,Rx/S (default is Rx/S)")
    # Select Sensor
    parser.add_option("-s", "--sensor", type="string", default="S2",
                  help="Select mode - S1,S2 (default is S2)")

    parser.add_option("-P", "--pfa", type="eng_float", default=0.05,
		     				help="choose the desired value for Probability of False\
		     				Alarm [default=%default]")



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



    (options, args) =  parser.parse_args()

    for mod in demods.values():
        mod.add_options(expert_grp)


    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)


    #start ignore
    if not options.real_time:
        realtime = False
    else:
        # 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"
    print options
    store_pkt = []
    tb = powerestimator(demods[options.modulation], rx_callback,options)
    try:
        tb.start()
        if options.type=='S' or options.type=='Rx/S':
            #Start the flow graph(in another thread...) and wait for a minute
            counter = 1
            skip = 1
            while 1:
                sleep(7)

                #Calculate mean and variance
                samples = tb.d.get_data()
                if len(samples) == 0:
                    #print 'Terminating operation because RSSI = NaN!!!!!!!!!!!!!'
                    continue
                spectrumdecision = 0

                if skip == 1:
                    skip = 0
                    continue

                randomvariablearray = []
                N = options.nblocks
                '''
                while(len(samples) >= N):
                    temparray = samples[0:N]
                    randomvariablearray.append(temparray.mean())
                    samples = samples[N:]
                '''
                store_pkt.append(pktno)
                if len(store_pkt) > 4:
                    del store_pkt[0:(len(store_pkt)-4)]

                mean = scipy.array(samples).mean()
                variance = scipy.array(samples, dtype = scipy.float64).var()
                #print len(samples)
                print '*'*80
                print 'Mean = ', 10*math.log10(mean), '\t\t\tVariance = ',10*math.log10(variance)


                q.put((options.args[-1],10*math.log10(mean),10*math.log10(variance)))



        tb.wait()
            #del tb
    except KeyboardInterrupt:
        tb.stop()
        print 'SIGTERM received.'
Example #56
0
def main():

    global n_rcvd, n_right, rcv_buffer

    n_rcvd = 0
    n_right = 0
    rcv_buffer = list()

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


#       print ' received ',

    def send_pkt(payload='', eof=False):
        return tb.txpath.send_pkt(payload, eof)

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

    parser.add_option("",
                      "--to-file",
                      default=None,
                      help="Output file for modulated samples")
    parser.add_option("-s",
                      "--size",
                      type="eng_float",
                      default=400,
                      help="set packet size [default=%default]")
    parser.add_option("-M",
                      "--megabytes",
                      type="eng_float",
                      default=1.0,
                      help="set megabytes to transmit [default=%default]")

    #rcv
    receive_path.add_options(parser, expert_grp)
    uhd_receiver.add_options(parser)
    digital.ofdm_demod.add_options(parser, expert_grp)
    #trans
    transmit_path.add_options(parser, expert_grp)
    digital.ofdm_mod.add_options(parser, expert_grp)
    uhd_transmitter.add_options(parser)

    (options, args) = parser.parse_args()

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

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

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

    tb.start()  # start flow graph
    #trans
    nbytes = int(1e3 * options.megabytes)
    n = 0
    pktno = 0
    pkt_size = int(options.size)

    if 1:
        while n < nbytes:
            if options.from_file is None:
                #data = (pkt_size - 2) * (pktno & 0xff)
                data = 'hellognuradio'
            else:
                data = source_file.read(pkt_size - 2)
                if data == '':
                    break

            payload = struct.pack('!H', pktno & 0xffff) + data

            send_pkt(payload)
            n += len(payload)
            print 'transmitting pktno = ', pktno
            pktno += 1

    send_pkt(eof=True)
    last_rcv_time = time.clock()
    while 1:
        while len(rcv_buffer) > 0:
            (pktno, payload) = rcv_buffer.pop(0)
            print 'pktno = ', pktno, 'payload = ', payload[2:]
        now = time.clock()
        #if not sleep, it seems it will chew up all CPU!
        time.sleep(0.3)
        if (now - last_rcv_time > 2):
            break
    print '########################TEST tx_rx_self FINISHED################################'
    print '########################NOW BEGIN TESTING carrier sense##########################'
    tb.rxpath.set_carrier_threshold(2)
    print 'threshold = ', tb.rxpath.carrier_threshold()
    while 1:
        print 'carrier sense : ', tb.rxpath.carrier_sensed()
        time.sleep(0.1)
    tb.wait()  # wait for it to finish
Example #57
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
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
Example #59
0
def main():

    global n_rcvd, n_right
        
    n_rcvd = 0
    n_right = 0

    def rx_callback(ok, payload, secs, frac_secs, cfo):
        global n_rcvd, n_right
        n_rcvd += 1
        (pktno,) = struct.unpack('!H', payload[0:2])
        #pktno = 0
        if ok:
            n_right += 1
        print "timestamp: %f \t ok: %r \t pktno: %d \t n_rcvd: %d \t n_right: %d \t cfo: %f" % (secs+frac_secs, ok, pktno, n_rcvd, n_right, cfo)
        if 1:
            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("","--external", 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("", "--log", action="store_true",
                      default=False,
                      help="Log all parts of flow graph to file (CAUTION: lots of data)")
    parser.add_option("", "--mode", type="string", default='benchmark',
                          help="Mode of OFDM_SYNC_PN: benchmark or fpnc")

    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