def main():
        
    parser = OptionParser(option_class=eng_option, conflict_handler="resolve")

    parser.add_option("", "--PHYport", type="int", default=8500 , help="Socket port [default=%default] ")
    parser.add_option("-n", "--node", type="intx", default=1, help="USRP2 node    [default=%default]")
    (options, args) = parser.parse_args ()
    
    print '\n',"----------------------------"
    print " PHY (RX) layer running ..."
    print "  (Ctrl + C) to exit"
    print "----------------------------",'\n'
        
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind((socket.gethostname(), options.PHYport))
    server.listen(1)
    
    # Launch all the buggers
    data = cola()
    ack = cola()
    rts = cola()
    cts = cola()
    bcn = cola()
    my_mac = mac.usrp2_node(options.node)   # Assign the MAC address of the node

        
    while 1:
        socket_cliente, datos_cliente = server.accept()
        hilo = Cliente(socket_cliente, datos_cliente,data,ack,rts,cts,bcn,my_mac)
        hilo.start()
Exemple #2
0
def main():

    parser = OptionParser(option_class=eng_option, conflict_handler="resolve")

    parser.add_option("",
                      "--PHYport",
                      type="int",
                      default=8500,
                      help="Socket port [default=%default] ")
    parser.add_option("-n",
                      "--node",
                      type="intx",
                      default=1,
                      help="USRP2 node    [default=%default]")
    (options, args) = parser.parse_args()

    print '\n', "----------------------------"
    print " PHY (RX) layer running ..."
    print "  (Ctrl + C) to exit"
    print "----------------------------", '\n'

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind((socket.gethostname(), options.PHYport))
    server.listen(1)

    # Launch all the buggers
    data = cola()
    ack = cola()
    rts = cola()
    cts = cola()
    bcn = cola()
    my_mac = mac.usrp2_node(options.node)  # Assign the MAC address of the node

    while 1:
        socket_cliente, datos_cliente = server.accept()
        hilo = Cliente(socket_cliente, datos_cliente, data, ack, rts, cts, bcn,
                       my_mac)
        hilo.start()
def main():
    def send_pkt(puerto, main_regime, sub_regime, eof=False):
        return tb.txpath.send_pkt(puerto, main_regime, sub_regime, eof)


#    def test_attribute(puerto, eof=False):
#        return tb.txpath.test_attribute(puerto, eof)

    parser = OptionParser(option_class=eng_option, usage="%prog: [options]")
    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("-f",
                      "--freq",
                      type="eng_float",
                      default=5.87e9,
                      help="set USRP2 carrier frequency, [default=%default]",
                      metavar="FREQ")
    parser.add_option("-w",
                      "--window-size",
                      type="int",
                      default=48,
                      help="set fir filter tap size [default=%default]")
    parser.add_option("-s",
                      "--sync-length",
                      type="int",
                      default=256,
                      help="sync length [default=%default]")
    parser.add_option("-W",
                      "--bandwidth",
                      type="eng_float",
                      default=20e6,
                      help="set symbol bandwidth [default=%default]\
                20 MHz  -> 802.11a/g, OFDM-symbol duration=4us, 10 MHz -> 802.11p, OFDM-symbolduration=8us"
                      )
    parser.add_option("-g",
                      "--gain",
                      type="int",
                      default=20,
                      help="set USRP2 Rx GAIN in [dB] [default=%default]")

    parser.add_option("",
                      "--regime",
                      type="string",
                      default="5",
                      help="set OFDM coderegime,    [default=%default]\
                        1 -> 6 (3) Mbit/s (BPSK r=0.5), \
                        2 -> 9 (4.5) Mbit/s (BPSK r=0.75), \
                        3 -> 12 (6) Mbit/s (QPSK r=0.5), \
                        4 -> 18 (9) Mbit/s (QPSK r=0.75), \
                        5 -> 24 (12) Mbit/s (QAM16 r=0.5), \
                        6 -> 36 (18) Mbit/s (QAM16 r=0.75), \
                        7 -> 48 (24) Mbit/s (QAM64 r=0.66), \
                        8 -> 54 (27) Mbit/s (QAM64 r=0.75)")

    parser.add_option("-G",
                      "--txgain",
                      type="int",
                      default=20,
                      help="set USRP2 Tx GAIN in [dB] [default=%default]")

    parser.add_option(
        "-n",
        "--norm",
        type="eng_float",
        default=0.4,
        help="set gain factor for complex baseband floats [default=%default]")
    parser.add_option("-N",
                      "--Node",
                      type="intx",
                      default=1,
                      help="USRP2 node    [default=%default]")

    parser.add_option(
        "-r",
        "--repetition",
        type="int",
        default=1,
        help=
        "set number of frame-copies to send, 0=infinite [default=%default] ")

    parser.add_option("-l",
                      "--log",
                      action="store_true",
                      default=True,
                      help="write debug-output of individual blocks to disk")

    parser.add_option("",
                      "--PHYRXport",
                      type="int",
                      default=8513,
                      help="Port used for PHY RX [default=%default] ")
    parser.add_option(
        "",
        "--PHYport",
        type="int",
        default=8013,
        help="Port used for MAC-->PHY communication [default=%default] ")

    parser.add_option("",
                      "--real-time",
                      action="store_true",
                      default=True,
                      help="Attempt to enable real-time scheduling")

    parser.add_option('-v',
                      "--verbose",
                      action="store_true",
                      default=False,
                      help="Print timing information, [default=%default]")

    parser.add_option("", "--nsym", type="int", default=1)
    parser.add_option("", "--modulation", type="string", default="bpsk")
    (options, args) = parser.parse_args()

    # Stream sockets to ensure no packet loss during PHY<-->MAC communication

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    #server.bind((socket.gethostname(), options.PHYport))
    server.bind((socket.gethostname(), options.PHYport))

    server.listen(1)  # PHY is ready to attend MAC requests

    phy_rx_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    phy_rx_server.bind((socket.gethostname(), options.PHYRXport))
    phy_rx_server.listen(1)

    print '\n', "-------------------------"
    print " PHY (TX) layer running ..."
    print " (Ctrl + C) to exit"
    print "-------------------------", '\n'

    my_mac = mac.usrp2_node(options.Node)  # Assign the MAC address of the node
    rxclient = threading.Thread(target=RX_Client,
                                args=(options, my_mac, phy_rx_server))
    rxclient.start()
    # Initial values of variables used in time measurement

    N_sym_prev = 4  # OFDM symbols of the previous packet sent
    N_sensings = 0  # Number of power measurements
    N_packets = 0  # Number of packets sent
    time_socket = 0  # Instant time of socket communication
    t_socket_TOTAL = 0  # Total time of socket communication
    T_sense_USRP2 = 0  # Time of the USRP2 measuring the power
    T_sense_PHY = 0  # Time elapsed in PHY layer due to a carrier sensing request
    T_transmit_USRP2 = 0  # USRP2 TX time
    T_configure_USRP2 = 0  # Time due to USRP2 graph management
    T_transmit_PHY = 0  # Time elapsed in PHY layer due to a packet tx request

    main_regime = int(options.regime)
    sub_regime = 0

    msgq = gr.msg_queue(1)
    first_time = True  # Is the first time to transmit?
    #fg_cca = sense_block(options)   # Set up the carrier sensing block for the first time.

    tb = wifi_rx(options, socket.gethostname(), msgq)
    tb.Start(True)

    while 1:
        socket_client, conn_addr = server.accept(
        )  # Waiting a request from the MAC layer
        arrived_packet = plcp.receive_from_mac(
            socket_client)  # Packet received from MAC
        print "Receive a packet from MAC......"
        print "Arrived packet header: %s......" % arrived_packet["HEADER"]
        print "Arrived DATA: %s......" % arrived_packet["DATA"]
        if (arrived_packet["HEADER"] == "PKT"):
            print "PHY receives a DATA frame from MAC......"
            t_socket = time.time(
            ) - arrived_packet["DATA"]["INFO"]["timestamp"]
            t_socket_TOTAL = t_socket_TOTAL + t_socket  #Update the time used in the socket communication.

            t_sendA = time.time()
            item = arrived_packet[
                "DATA"]  # Copy the packet to send from the MAC message
            info = item["INFO"]
            N_sym = info["N_sym"]  # Read N_sym and add N_sym to options
            mod = info["modulation"]

            options.nsym = N_sym
            options.modulation = mod

            print "Re-setting USRP2 graph!"
            tb = transmitter_block(
                options
            )  # If necessary, update the transmit flow-graph depending to the new OFDM parameters
            r = gr.enable_realtime_scheduling()
            if r != gr.RT_OK:
                print "Warning: failed to enable realtime scheduling"
            t_2 = time.time()
            tb.start()  # Send packet procedure starts
            #test_attribute(item,eof=False)
            t_sendB = time.time()
            send_pkt(
                item, main_regime, sub_regime, eof=False
            )  # 'item' is a dictionary which contents the packet to transmit and other information
            print "Complete send_pkt(item,eof=False)"
            send_pkt("", main_regime, sub_regime, eof=True)
            print "Complete send_pkt(" ",eof=True)"
            t_sendC = time.time()
            print "t_sendC"
            tb.wait()  # Wait until USRP2 finishes the TX-graph
            print "PHY successfully transmit one frame!!!!!!!"
            t_sendD = time.time()
            if options.verbose:
                print "Time elapsed on graph configuration (TX Packet) = \t", (
                    t_sendB - t_2)
            T_transmit_USRP2 = T_transmit_USRP2 + t_sendC - t_sendB
            T_configure_USRP2 = T_configure_USRP2 + t_sendD - t_sendA - (
                t_sendC - t_sendB)
            T_transmit_PHY = T_transmit_PHY + t_sendD - t_sendA

            # set values for the next packet tx request
            first_time = False
            N_sym_prev = N_sym  # Keep a record of the OFDM symbols' Number
            N_packets += 1

        # Carrier sensing request
        if (arrived_packet["HEADER"] == "CCA"):
            #print "PHY receives a CCA from MAC......"
            t_senseA = time.time()
            #print "Breakpoint 1......"
            msgq.flush()
            #print "Breakpoint 2......"
            t_reconfig = time.time() - t_senseA
            #print "Breakpoint 3......"
            m = msgq.delete_head()
            #print "Breakpoint 4......"
            t = m.to_string()
            #print "The head deleted is %s......" %t
            #print "Breakpoint 5......"
            msgdata = struct.unpack('%df' % (int(m.arg2()), ), t)
            #print "Breakpoint 6......"
            sensed_power = msgdata[0]
            #print "Breakpoint 7......"
            t_senseB = time.time()

            # PHY responds with the power measured to the MAC
            #print "PHY creates CCA......"
            packet = plcp.create_packet("CCA", sensed_power)
            #print "PHY sends CCA to MAC......"
            plcp.send_to_mac(socket_client, packet)
            #print "MAC finishes sending CCA to MAC......"
            t_senseC = time.time()
            T_sense_USRP2 = T_sense_USRP2 + (t_senseB - t_senseA)
            T_sense_PHY = T_sense_PHY + (t_senseC - t_senseA)
            N_sensings += 1
            if options.verbose:
                print "Time elapsed on graph configuration (Carrier Sensing) = \t", t_reconfig

        if (arrived_packet["HEADER"] == "RATE"):
            header_pkt = arrived_packet["DATA"]
            print "The header of the pkt is %s......................" % header_pkt
            main_regime, sub_regime = v2r(int(header_pkt))
            options.regime = str(main_regime)
            print "Now the rate is %s..............................." % options.regime

        # MAC requests an incoming packet to the PHY
        if (arrived_packet["HEADER"] == "TAIL"):
            header_pkt = arrived_packet["DATA"]

            len_data = data.length()
            len_ack = ack.length()
            len_rts = rts.length()
            len_cts = cts.length()

            if (header_pkt
                    == "DATA") and len_data > 0:  # There are Data packets?
                #print "Header is DATA......"
                data.elements.reverse()
                x = data.read(0)
                phy_pkt = plcp.create_packet("YES", x)
                data.pop()
                data.elements.reverse()

            elif header_pkt == "ACK" and len_ack > 0:  # There are ACK packets?
                ack.elements.reverse()
                x = ack.read(0)
                phy_pkt = plcp.create_packet("YES", x)
                ack.pop()
                ack.elements.reverse()

            elif header_pkt == "RTS" and len_rts > 0:  # There are RTS packets?
                rts.elements.reverse()
                x = rts.read(0)
                phy_pkt = plcp.create_packet("YES", x)
                rts.pop()
                rts.elements.reverse()
            elif header_pkt == "CTS" and len_cts > 0:  # There are CTS packets?
                cts.elements.reverse()
                x = cts.read(0)
                phy_pkt = plcp.create_packet("YES", x)
                cts.pop()
                cts.elements.reverse()
            else:  # There are not packets
                #print "There are no packets in PHY......"
                phy_pkt = plcp.create_packet("NO", [])
            #print "PHY sends notifications to MAC......"
            plcp.send_to_mac(
                socket_client,
                phy_pkt)  # Send the result (PHY packet) to MAC layer
        #socket_client.close()

        if options.verbose:
            print "===================== Average statistics ===================="
            print "Number of Carrier Sensing Requests = ", N_sensings
            if N_sensings > 0:
                print "Time spent by USRP2 on sensing channel = \t", T_sense_USRP2 / N_sensings
                print "Time spent by PHY layer on sensing channel = \t", T_sense_PHY / N_sensings
            print "============================================================="
            print "Number of packets transmitted = ", N_packets
            if N_packets > 1:
                print "Time spent by USRP2 on sending a packet = \t", T_transmit_USRP2 / N_packets
                print "Time spent by USRP2 on configuring the graphs\t", T_configure_USRP2 / N_packets
                print "Time spent by PHY on sending a packet = \t", T_transmit_PHY / N_packets
                print "Time spent on Socket Communication = \t", t_socket_TOTAL / N_packets
            print "============================================================="

    tb.Wait()
Exemple #4
0
def main():
    parser = OptionParser(option_class=eng_option, conflict_handler="resolve")
    parser.add_option("",
                      "--PHYport",
                      type="intx",
                      default=8013,
                      help="PHY communication socket port, [default=%default]")
    parser.add_option("",
                      "--MACport",
                      type="intx",
                      default=8001,
                      help="MAC communication socket port, [default=%default]")
    parser.add_option(
        "-i",
        "--interp",
        type="intx",
        default=10,
        help="USRP2 interpolation factor value, [default=%default]\
		        5  -> 802.11a/g, OFDM T_Symbol=4us, \
		        10 -> 802.11p, OFDM T_Symbol=8us")
    parser.add_option("",
                      "--regime",
                      type="string",
                      default="5",
                      help="OFDM regimecode    [default=%default]\
		                1 -> 6 (3) Mbit/s (BPSK r=0.5), \
		                2 -> 9 (4.5) Mbit/s (BPSK r=0.75), \
		                3 -> 12 (6) Mbit/s (QPSK r=0.5), \
		                4 -> 18 (9) Mbit/s (QPSK r=0.75), \
		                  5 -> 24 (12) Mbit/s (QAM16 r=0.5), \
		                6 -> 36 (18) Mbit/s (QAM16 r=0.75), \
		                7 -> 48 (24) Mbit/s (QAM64 r=0.66), \
		                8 -> 54 (27) Mbit/s (QAM64 r=0.75)")
    parser.add_option("-n",
                      "--node",
                      type="intx",
                      default=1,
                      help="Number of USRP2 node, [default=%default]")
    parser.add_option("",
                      "--beta",
                      type="float",
                      default=150000,
                      help="Scaling Time Parameter, [default=%default]")
    parser.add_option("-t",
                      "--time_slot",
                      type="float",
                      default=9e-6,
                      help="Time slot value, [default=%default]")
    parser.add_option(
        "-B",
        "--BI",
        type="float",
        default=1,
        help="Beacon Interval (BI) value in seconds, [default=%default]")
    parser.add_option(
        "-S",
        "--SIFS",
        type="float",
        default=16e-6,
        help="Short Inter-frame space (SIFS) value, [default=%default]")
    parser.add_option('',
                      "--retx",
                      action="store_true",
                      default=False,
                      help="Retransmissions enabled, [default=%default]")
    parser.add_option('',
                      "--RTS",
                      action="store_true",
                      default=False,
                      help="RTS-threshold enabled, [default=%default]")
    parser.add_option('-v',
                      "--V",
                      action="store_true",
                      default=True,
                      help="Print debug information, [default=%default]")
    (options, args) = parser.parse_args()

    my_mac = MAC.usrp2_node(options.node)  # MAC address for this node
    dest_mac = MAC.usrp2_node(
        2)  # Dummy value (updated when an incoming packet arrives)

    beta = options.beta  # scaling time parameter
    tslot = options.time_slot * beta
    SIFS = options.SIFS * beta
    DIFS = SIFS + 2 * tslot
    Preamble = DIFS  #16e-6
    PLCP_header = 4e-6 * beta
    ACK_time = Preamble + PLCP_header
    CW_min = 15
    CW_max = 1023
    RTS_THRESHOLD = 150
    dot11FragmentationTh = 1036

    # TX time estimation for a CTS and an ACK packet
    empty_values = {"duration": 0, "mac_ra": my_mac, "timestamp": time.time()}
    CTS_empty = MAC.generate_pkt("CTS", options.interp, options.regime,
                                 empty_values)
    T_cts = CTS_empty["INFO"]["txtime"]
    ACK_empty = MAC.generate_pkt("ACK", options.interp, options.regime,
                                 empty_values)
    T_ack = ACK_empty["INFO"]["txtime"]

    # Set socket ports
    PHY_port = options.PHYport
    #PHYRX_port = options.PHYRXport
    MAC_port = options.MACport

    # Variables involving MAC tests
    testing = False  # Testing mode active, used to conduct trials
    N_TESTS = 1000  # Number of tests
    N_TESTS_INI = N_TESTS
    LONG_TESTS = 20  # Payload length for tests
    payload_test = "0000" + LONG_TESTS * '1'  # Payload for tests
    test_with_sensing = True  # Carrier Sensing (CS) allowed during the test
    total_processing_time = 0  # Total processing time
    t_sense_mean = 0  # CS average time
    t_csense = 0  # CS time
    t_MAC = 0  # MAC time
    t_MAC_mean = 0  # MAC average time
    packet_i = 0  # Packets sent counter
    n_sensing = 0  # Number of CS performed

    # 'State' controls the state of the MAC
    State = "IDLE"

    # Initial Conditions of the Finite State Machine
    NAV = 0  # Network Allocation Vector
    N_RETRIES = 0  # Retries to send a packet counter
    busy_in_wfd = False  # Busy in Wait_for_DIFS state
    BO_frozen = "NO"  # Backoff frozen
    TX_attempts = 0  # Tries to send a packet counter
    CTS_failed = False  # CTS reception failed
    chan = "FREE"  # Channel state = IDDLE
    N_SEQ = 0  # Sequence number counter
    N_FRAG = 0  # Fragment number counter
    first_tx = True  # Is the first attempt to send a packet?
    frag_count = 0  # Counter used during fragmentation
    data_temp_reass = ""  # Initial variable to perform de re-assembly process
    verbose = True  # Shows when the MAC is in 'IDDLE' state
    beaconing = False  # Is ON the Beaconing process?
    fragmenting = 0  # Is the packet received a fragment?

    if options.V:
        print "============================================="
        print " \t  MAC layer: DCF + RTS/CTS"
        print "============================================="
        print "MAC address:", MAC.which_dir(my_mac)
        print "Rate = ", options.regime
        print "tslot(s): %f \t SIFS(s): %f" % (tslot, SIFS)
        print "DIFS(s): %f \t T_ACK(s): %f" % (DIFS, ACK_time)
        print "pseudo-random exp. BACKOFF [%i,%i]" % (CW_min, CW_max)
        if options.RTS:
            print "RTS/CTS: enabled"
            print "\t with RTS Threshold(Bytes): %i \t" % RTS_THRESHOLD
        else:
            print "RTS/CTS: disabled"
        print "Fragmentation Threshold (Bytes):", dot11FragmentationTh
        if options.retx: print "Retransmissions: enabled"
        else: print "Retransmissions: disabled"
        print "Scaling time parameter = ", beta
        print "============================================="
def main():
    parser = OptionParser(option_class=eng_option, conflict_handler="resolve")
    parser.add_option("", "--PHYport", type="intx", default=8013,
                          help="PHY communication socket port, [default=%default]")
    parser.add_option("", "--MACport", type="intx", default=8001,
                          help="MAC communication socket port, [default=%default]")
    parser.add_option("-i", "--interp", type="intx", default=10,
                          help="USRP2 interpolation factor value, [default=%default]\
                5  -> 802.11a/g, OFDM T_Symbol=4us, \
                10 -> 802.11p, OFDM T_Symbol=8us")
    parser.add_option("", "--regime", type="string", default="1",
                          help="OFDM regimecode    [default=%default]\
                        1 -> 6 (3) Mbit/s (BPSK r=0.5), \
                        2 -> 9 (4.5) Mbit/s (BPSK r=0.75), \
                        3 -> 12 (6) Mbit/s (QPSK r=0.5), \
                        4 -> 18 (9) Mbit/s (QPSK r=0.75), \
                          5 -> 24 (12) Mbit/s (QAM16 r=0.5), \
                        6 -> 36 (18) Mbit/s (QAM16 r=0.75), \
                        7 -> 48 (24) Mbit/s (QAM64 r=0.66), \
                        8 -> 54 (27) Mbit/s (QAM64 r=0.75)")
    parser.add_option("-n", "--node", type="intx", default=1,
                          help="Number of USRP2 node, [default=%default]")
    parser.add_option("", "--beta", type="float", default=50000,
                          help="Scaling Time Parameter, [default=%default]")
    parser.add_option("-t", "--time_slot", type="float", default=9e-6,
                          help="Time slot value, [default=%default]")
    parser.add_option("-B", "--BI", type="float", default=1,
                          help="Beacon Interval (BI) value in seconds, [default=%default]")
    parser.add_option("-S", "--SIFS", type="float", default=16e-6,
                          help="Short Inter-frame space (SIFS) value, [default=%default]")
    parser.add_option('', "--retx", action="store_true", default=False,
                        help="Retransmissions enabled, [default=%default]")
    parser.add_option('', "--RTS", action="store_true", default=True,
                        help="RTS-threshold enabled, [default=%default]")
    parser.add_option('-v', "--V", action="store_true", default=False,
                        help="Print debug information, [default=%default]")
    (options, args) = parser.parse_args ()
            
    my_mac = MAC.usrp2_node(options.node)   # MAC address for this node
    dest_mac = MAC.usrp2_node(2)            # Dummy value (updated when an incoming packet arrives)
     
    """
    IEEE 802.11-a MAC parameters
    """
    beta = options.beta # scaling time parameter
    tslot = options.time_slot * beta
    SIFS = options.SIFS * beta
    DIFS = SIFS + 2 * tslot
    Preamble = DIFS #16e-6
    PLCP_header = 4e-6 * beta
    ACK_time = Preamble + PLCP_header
    CW_min = 15
    CW_max = 1023
    RTS_THRESHOLD = 150
    dot11FragmentationTh = 1036

    # TX time estimation for a CTS and an ACK packet
    empty_values = {"duration":0, "mac_ra":my_mac, "timestamp":time.time()}  
    CTS_empty = MAC.generate_pkt("CTS", options.interp, options.regime, empty_values)
    T_cts = CTS_empty["INFO"]["txtime"]
    ACK_empty = MAC.generate_pkt("ACK", options.interp, options.regime, empty_values)
    T_ack = ACK_empty["INFO"]["txtime"]
    
    # Set socket ports
    PHY_port = options.PHYport
    #PHYRX_port = options.PHYRXport
    MAC_port = options.MACport
    
    # Variables involving MAC tests
    testing = False                         # Testing mode active, used to conduct trials
    N_TESTS = 1000                          # Number of tests
    N_TESTS_INI = N_TESTS           
    LONG_TESTS = 20                         # Payload length for tests
    payload_test = "0000" + LONG_TESTS*'1'  # Payload for tests
    test_with_sensing = True                 # Carrier Sensing (CS) allowed during the test
    total_processing_time = 0          # Total processing time
    t_sense_mean = 0                     # CS average time
    t_csense = 0                           # CS time
    t_MAC = 0                               # MAC time
    t_MAC_mean = 0                         # MAC average time
    packet_i=0                             # Packets sent counter
    n_sensing = 0                           # Number of CS performed
    
    # 'State' controls the state of the MAC
    State = "IDLE" 
    
    # Initial Conditions of the Finite State Machine
    NAV = 0                 # Network Allocation Vector           
    N_RETRIES = 0           # Retries to send a packet counter
    busy_in_wfd = False  # Busy in Wait_for_DIFS state
    BO_frozen = "NO"     # Backoff frozen    
    TX_attempts = 0             # Tries to send a packet counter
    CTS_failed = False      # CTS reception failed
    chan = "FREE"          # Channel state = IDDLE
    N_SEQ = 0               # Sequence number counter
    N_FRAG = 0              # Fragment number counter
    first_tx = True         # Is the first attempt to send a packet?
    frag_count = 0         # Counter used during fragmentation
    data_temp_reass = ""     # Initial variable to perform de re-assembly process
    verbose = True          # Shows when the MAC is in 'IDDLE' state
    beaconing = False       # Is ON the Beaconing process?
    fragmenting = 0         # Is the packet received a fragment?
    
    if options.V:
        print "============================================="
        print " \t  MAC layer: DCF + RTS/CTS"
        print "============================================="
        print "MAC address:",MAC.which_dir(my_mac)
        print "Rate = ",options.regime
        print "tslot(s): %f \t SIFS(s): %f"%(tslot,SIFS)
        print "DIFS(s): %f \t T_ACK(s): %f"%(DIFS, ACK_time)
        print "pseudo-random exp. BACKOFF [%i,%i]"%(CW_min, CW_max)
        if options.RTS: 
            print "RTS/CTS: enabled"
            print "\t with RTS Threshold(Bytes): %i \t" %RTS_THRESHOLD
        else: print "RTS/CTS: disabled"
        print "Fragmentation Threshold (Bytes):",dot11FragmentationTh
        if options.retx: print "Retransmissions: enabled"
        else: print "Retransmissions: disabled"
        print "Scaling time parameter = ",beta
        print "============================================="
 numero = 1          # number of tests to perform
 test = True
 
 print '\n',"----------------------------------"
 print " PHY Fragmented traffic generator"
 print " (Ctrl + C) to exit"
 print "----------------------------------",'\n'
 
 while test== True:
     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     s.connect((socket.gethostname(), 8500))
     N_SEQ = random.randint(0,4095)  # Assign randomly a sequence number
     N_FRAG = 0                      # First fragment will always be 0
     
     # Values for Fragmented Data packets
     valores_DATA12={"payload":"HELLO_WO", "address1":MAC.usrp2_node(1),"address2":MAC.usrp2_node(2),"N_SEQ":500, "N_FRAG":0,"timestamp":time.time()}
     valores_DATA13={"payload":"RLD_FRAG", "address1":MAC.usrp2_node(1),"address2":MAC.usrp2_node(3),"N_SEQ":501, "N_FRAG":1,"timestamp":time.time()}
     valores_DATA14={"payload":"MENT_TX_", "address1":MAC.usrp2_node(1),"address2":MAC.usrp2_node(4),"N_SEQ":502, "N_FRAG":2,"timestamp":time.time()}
     valores_DATA4={"payload":"TEST!!", "address1":MAC.usrp2_node(1),"address2":MAC.usrp2_node(4),"N_SEQ":499, "N_FRAG":0,"timestamp":time.time()}
     
     # Generate the Fragmented Data packets with the selected values
     paquete1=MAC.ftw_make("DATA_FRAG",valores_DATA12,"1",4)
     paquete2=MAC.ftw_make("DATA_FRAG",valores_DATA13,"1",4)
     paquete3=MAC.ftw_make("DATA",valores_DATA14,"1",4)
     paquete4=MAC.ftw_make("DATA",valores_DATA4,"1",4)
     
     # Transmitting sequence
     if numero == 0:
         pkt = crear_paquete("DATA",paquete4)
         numero += 4
     elif numero == 1:
Exemple #7
0
def main():
    def send_pkt(puerto, eof=False):
        return tb.txpath.send_pkt(puerto, eof)
    parser = OptionParser(option_class=eng_option, usage="%prog: [options]")
    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("-f", "--freq", type="eng_float",
                          default = 5.825e9, help="set USRP2 carrier frequency, [default=%default]",
                          metavar="FREQ")
    parser.add_option("-w", "--window-size", type="int", default=48 , help = "set fir filter tap size [default=%default]")
    parser.add_option("-s", "--sync-length", type="int", default=256 , help = "sync length [default=%default]")
    parser.add_option("-W", "--bandwidth", type="eng_float", default=1e7, help="set symbol bandwidth [default=%default]\
                20 MHz  -> 802.11a/g, OFDM-symbol duration=4us, 10 MHz -> 802.11p, OFDM-symbolduration=8us")
    parser.add_option("-g", "--gain", type="int", default=0 , help = "set USRP2 Rx GAIN in [dB] [default=%default]")

    parser.add_option("", "--regime", type="string", default="1",
                          help="set OFDM coderegime,    [default=%default]\
                        1 -> 6 (3) Mbit/s (BPSK r=0.5), \
                        2 -> 9 (4.5) Mbit/s (BPSK r=0.75), \
                        3 -> 12 (6) Mbit/s (QPSK r=0.5), \
                        4 -> 18 (9) Mbit/s (QPSK r=0.75), \
                        5 -> 24 (12) Mbit/s (QAM16 r=0.5), \
                        6 -> 36 (18) Mbit/s (QAM16 r=0.75), \
                        7 -> 48 (24) Mbit/s (QAM64 r=0.66), \
                        8 -> 54 (27) Mbit/s (QAM64 r=0.75)")

    parser.add_option("-G", "--txgain", type="int", default=10 , help = "set USRP2 Tx GAIN in [dB] [default=%default]")

    parser.add_option("-n", "--norm", type="eng_float", default=0.3 , help="set gain factor for complex baseband floats [default=%default]")
    parser.add_option("-N", "--Node", type="intx", default=1, help="USRP2 node    [default=%default]")

    parser.add_option("-r", "--repetition", type="int", default=1 , help="set number of frame-copies to send, 0=infinite [default=%default] ")

    parser.add_option("-l", "--log", action="store_true", default=False, help="write debug-output of individual blocks to disk")

    parser.add_option("", "--PHYRXport", type="int", default=8513 , help="Port used for PHY RX [default=%default] ")
    parser.add_option("", "--PHYport", type="int", default=8013 , help="Port used for MAC-->PHY communication [default=%default] ")

    parser.add_option("", "--real-time", action="store_true", default=False,
                      help="Attempt to enable real-time scheduling")

    parser.add_option('-v', "--verbose", action="store_true", default=False,
                        help="Print timing information, [default=%default]")
    
    parser.add_option("", "--nsym", type="int", default=1)
    parser.add_option("", "--modulation", type="string", default="bpsk")
    (options, args) = parser.parse_args()

    # Stream sockets to ensure no packet loss during PHY<-->MAC communication

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.bind((socket.gethostname(), options.PHYport))
    server.listen(1)    # PHY is ready to attend MAC requests

    phy_rx_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    phy_rx_server.bind((socket.gethostname(), options.PHYRXport))
    phy_rx_server.listen(1)

    
    print '\n',"-------------------------"
    print " PHY (TX) layer running ..."
    print " (Ctrl + C) to exit"
    print "-------------------------",'\n'

    my_mac = mac.usrp2_node(options.Node)   # Assign the MAC address of the node
    rxclient = threading.Thread(target=RX_Client, args=(options,my_mac,phy_rx_server))
    rxclient.start()
    # Initial values of variables used in time measurement

    N_sym_prev=4             # OFDM symbols of the previous packet sent
    N_sensings = 0          # Number of power measurements
    N_packets = 0          # Number of packets sent
    time_socket = 0       # Instant time of socket communication
    t_socket_TOTAL = 0      # Total time of socket communication
    T_sense_USRP2 = 0     # Time of the USRP2 measuring the power
    T_sense_PHY = 0       # Time elapsed in PHY layer due to a carrier sensing request 
    T_transmit_USRP2 = 0  # USRP2 TX time 
    T_configure_USRP2 = 0  # Time due to USRP2 graph management
    T_transmit_PHY = 0    # Time elapsed in PHY layer due to a packet tx request
    
    msgq = gr.msg_queue(1)


    first_time = True               # Is the first time to transmit?
    #fg_cca = sense_block(options)   # Set up the carrier sensing block for the first time.
    rb = receiver_block(options,socket.gethostname(),msgq)
    rb.start()

    while 1:

        socket_client, conn_addr = server.accept()     # Waiting a request from the MAC layer
        arrived_packet=plcp.receive_from_mac(socket_client) # Packet received from MAC
        if (arrived_packet["HEADER"]=="PKT"): 
            t_socket = time.time()-arrived_packet["DATA"]["INFO"]["timestamp"]
            t_socket_TOTAL =t_socket_TOTAL + t_socket   #Update the time used in the socket communication.


            t_sendA = time.time()
            item=arrived_packet["DATA"]  # Copy the packet to send from the MAC message 
            info = item["INFO"]
            N_sym=info["N_sym"] # Read N_sym and add N_sym to options
            mod = info["modulation"]    

            options.nsym = N_sym
            options.modulation=mod


            print "Re-setting USRP2 graph!"
            tb = transmitter_block(options) # If necessary, update the transmit flow-graph depending to the new OFDM parameters
            r = gr.enable_realtime_scheduling()    
            if r != gr.RT_OK:
                print "Warning: failed to enable realtime scheduling" 
            t_2 = time.time()
            tb.start()                  # Send packet procedure starts
            t_sendB= time.time()
            send_pkt(item,eof=False)   # 'item' is a dictionary which contents the packet to transmit and other information 
            send_pkt("",eof=True)
            t_sendC = time.time()     
            tb.wait()                   # Wait until USRP2 finishes the TX-graph 
            t_sendD= time.time()
            if options.verbose: print "Time elapsed on graph configuration (TX Packet) = \t", (t_sendB - t_2)
            T_transmit_USRP2 = T_transmit_USRP2 + t_sendC-t_sendB
            T_configure_USRP2 = T_configure_USRP2 + t_sendD-t_sendA - (t_sendC-t_sendB)
            T_transmit_PHY = T_transmit_PHY + t_sendD-t_sendA 

            # set values for the next packet tx request
            first_time=False
            N_sym_prev = N_sym       # Keep a record of the OFDM symbols' Number
            N_packets += 1


        # Carrier sensing request
        if (arrived_packet["HEADER"]=="CCA"):
            t_senseA = time.time()
            msgq.flush()
            t_reconfig = time.time()-t_senseA
            m=msgq.delete_head()
            t = m.to_string()
            msgdata = struct.unpack('%df' % (int(m.arg2()),), t)
            sensed_power=msgdata[0]
            t_senseB = time.time()

            # PHY responds with the power measured to the MAC
            packet=plcp.create_packet("CCA",sensed_power)
            plcp.send_to_mac(socket_client,packet)
            t_senseC = time.time()
            T_sense_USRP2 = T_sense_USRP2 + (t_senseB - t_senseA)
            T_sense_PHY = T_sense_PHY + (t_senseC - t_senseA)
            N_sensings +=1 
            if options.verbose: print "Time elapsed on graph configuration (Carrier Sensing) = \t", t_reconfig

            
        # MAC requests an incoming packet to the PHY
        if (arrived_packet["HEADER"]=="TAIL"): 
            header_pkt = arrived_packet["DATA"]
            
            len_data = data.length()
            len_ack = ack.length()
            len_rts = rts.length()
            len_cts = cts.length()
            
            if (header_pkt == "DATA") and len_data>0: # There are Data packets?
                data.elements.reverse()
                x=data.read(0)
                phy_pkt = plcp.create_packet("YES",x)
                data.pop()
                data.elements.reverse()
                           
            elif header_pkt == "ACK" and len_ack>0:   # There are ACK packets?
                ack.elements.reverse()
                x=ack.read(0)
                phy_pkt = plcp.create_packet("YES",x)
                ack.pop()
                ack.elements.reverse()
                       
            elif header_pkt == "RTS" and len_rts>0:   # There are RTS packets?
                rts.elements.reverse()
                x=rts.read(0)
                phy_pkt = plcp.create_packet("YES",x)
                rts.pop()
                rts.elements.reverse()           
            elif header_pkt == "CTS" and len_cts>0:   # There are CTS packets?
                cts.elements.reverse()
                x=cts.read(0)
                phy_pkt = plcp.create_packet("YES",x)
                cts.pop()
                cts.elements.reverse()
            else:                                   # There are not packets
                phy_pkt = plcp.create_packet("NO",[])
            plcp.send_to_mac(socket_client,phy_pkt)  # Send the result (PHY packet) to MAC layer
        socket_client.close()

        
        if options.verbose:
            print "===================== Average statistics ===================="
            print "Number of Carrier Sensing Requests = ",N_sensings
            if N_sensings>0:
                print "Time spent by USRP2 on sensing channel = \t",T_sense_USRP2/N_sensings
                print "Time spent by PHY layer on sensing channel = \t",T_sense_PHY/N_sensings
            print "============================================================="
            print "Number of packets transmitted = ",N_packets
            if N_packets>1:
                print "Time spent by USRP2 on sending a packet = \t",T_transmit_USRP2/N_packets 
                print "Time spent by USRP2 on configuring the graphs\t",T_configure_USRP2/N_packets
                print "Time spent by PHY on sending a packet = \t",T_transmit_PHY/N_packets
                print "Time spent on Socket Communication = \t", t_socket_TOTAL/N_packets
            print "============================================================="
            
    rb.wait()
def main():
    parser = OptionParser(option_class=eng_option, usage="%prog: [options]")
    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("-f", "--freq", type="eng_float",
                          default = 5.825e9, help="set USRP2 carrier frequency, [default=%default]",
                          metavar="FREQ")
    parser.add_option("-w", "--window-size", type="int", default=48 , help = "set fir filter tap size [default=%default]")
    parser.add_option("-s", "--sync-length", type="int", default=256 , help = "sync length [default=%default]")
    parser.add_option("-W", "--bandwidth", type="eng_float", default=1e7, help="set symbol bandwidth [default=%default]\
                20 MHz  -> 802.11a/g, OFDM-symbol duration=4us, 10 MHz -> 802.11p, OFDM-symbolduration=8us")
    parser.add_option("-g", "--gain", type="int", default=0 , help = "set USRP2 Rx GAIN in [dB] [default=%default]")

    parser.add_option("", "--regime", type="string", default="1",
                          help="set OFDM coderegime,    [default=%default]\
                        1 -> 6 (3) Mbit/s (BPSK r=0.5), \
                        2 -> 9 (4.5) Mbit/s (BPSK r=0.75), \
                        3 -> 12 (6) Mbit/s (QPSK r=0.5), \
                        4 -> 18 (9) Mbit/s (QPSK r=0.75), \
                        5 -> 24 (12) Mbit/s (QAM16 r=0.5), \
                        6 -> 36 (18) Mbit/s (QAM16 r=0.75), \
                        7 -> 48 (24) Mbit/s (QAM64 r=0.66), \
                        8 -> 54 (27) Mbit/s (QAM64 r=0.75)")

    parser.add_option("-G", "--txgain", type="int", default=10 , help = "set USRP2 Tx GAIN in [dB] [default=%default]")

    parser.add_option("-n", "--norm", type="eng_float", default=0.3 , help="set gain factor for complex baseband floats [default=%default]")
    parser.add_option("-N", "--Node", type="intx", default=1, help="USRP2 node    [default=%default]")

    parser.add_option("-r", "--repetition", type="int", default=1 , help="set number of frame-copies to send, 0=infinite [default=%default] ")

    parser.add_option("-l", "--log", action="store_true", default=False, help="write debug-output of individual blocks to disk")

    parser.add_option("", "--PHYRXport", type="int", default=8513 , help="Port used for PHY RX [default=%default] ")
    parser.add_option("", "--PHYport", type="int", default=8013 , help="Port used for MAC-->PHY communication [default=%default] ")

    parser.add_option("", "--tune-delay", type="eng_float", default=1e-4, metavar="SECS",
                      help="Carrier sensing parameter. Time to delay (in seconds) after changing frequency [default=%default]")

    parser.add_option("", "--dwell-delay", type="eng_float", default=1e-3, metavar="SECS",
                      help="Carrier sensing parameter. Time to dwell (in seconds) at a given frequncy [default=%default]")

    parser.add_option("-F", "--fft-size", type="int", default=256,
                      help="specify number of FFT bins [default=%default]")

    parser.add_option("-d", "--decim", type="intx", default=16,
                      help="set the decimation value [default=%default]")

    parser.add_option("", "--real-time", action="store_true", default=False,
                      help="Attempt to enable real-time scheduling")

    parser.add_option('-v', "--verbose", action="store_true", default=False,
                        help="Print timing information, [default=%default]")
    
    parser.add_option("", "--nsym", type="int", default=1)
    parser.add_option("", "--modulation", type="string", default="bpsk")
    (options, args) = parser.parse_args()


    phy_rx_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    phy_rx_server.bind((socket.gethostname(), options.PHYRXport))
    phy_rx_server.listen(1)

    my_mac = mac.usrp2_node(options.Node)   # Assign the MAC address of the node
    rxclient = threading.Thread(target=RX_Client, args=(options,my_mac,phy_rx_server))
    rxclient.start()

    rb = receiver_block(options,socket.gethostname())
    rb.start()

    while 1:
        len_other=other.length()
        if (len_other>0): 
            other.elements.reverse()
            x=other.read(0)
            other.pop()
            other.elements.reverse()
            print x
            #rb.stop()
            #rb.wait()
            #rb.start()

            
    rb.stop()
    rb.wait()
def main():
    parser = OptionParser(option_class=eng_option, conflict_handler="resolve")
    parser.add_option("-n", "--node", type="intx", default=1, help="USRP2 node    [default=%default]")
    (options, args) = parser.parse_args ()
    def crear_paquete(tipo,data):
        packet={"TIPO":tipo,"DATOS":data}
        return packet
    #for loop used to test the correct RTS/CTS functionality, this limits the number of packets that arrived to the station
    n_packets = 0   
    print '\n',"-------------------------"
    print " PHY traffic generator ..."
    print " (Ctrl + C) to exit"
    print "-------------------------",'\n'
    for i in range (1,100):
        while n_packets < 100:  # ADJUST THE NUMBER OF PACKETS GENERATED 
            #n_packets+=1        # NOTE: commented to force infinite packet generation
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((socket.gethostname(), 8500))
            N_SEQ = random.randint(0,4095)  # Assign sequence and fragment number
            N_FRAG = 0
            
            # Values for different frames based on the MAC address of each USRP2
            
            valores_B1 = {"address2":MAC.usrp2_node(1), "N_SEQ":N_SEQ,"N_FRAG":0 ,"BI":1,"timestamp":time.time()}
            valores_B2 = {"address2":MAC.usrp2_node(2), "N_SEQ":N_SEQ,"N_FRAG":0 ,"BI":1,"timestamp":time.time()}
            valores_B3 = {"address2":MAC.usrp2_node(3), "N_SEQ":N_SEQ,"N_FRAG":0 ,"BI":1,"timestamp":time.time()}
            valores_B4 = {"address2":MAC.usrp2_node(4), "N_SEQ":N_SEQ,"N_FRAG":0 ,"BI":1,"timestamp":time.time()}
                
            valores_CTS1 = {"duration":0, "mac_ra":MAC.usrp2_node(1),"timestamp":time.time()}
            valores_CTS2 = {"duration":0, "mac_ra":MAC.usrp2_node(2),"timestamp":time.time()}
            valores_CTS3 = {"duration":0, "mac_ra":MAC.usrp2_node(3),"timestamp":time.time()}
            valores_CTS4 = {"duration":0, "mac_ra":MAC.usrp2_node(4),"timestamp":time.time()}
            
            valores_ACK1 = {"duration":0, "mac_ra": MAC.usrp2_node(1),"timestamp":time.time()}
            valores_ACK2 = {"duration":0, "mac_ra": MAC.usrp2_node(2),"timestamp":time.time()}
            valores_ACK3 = {"duration":0, "mac_ra": MAC.usrp2_node(3),"timestamp":time.time()}
            valores_ACK4 = {"duration":0, "mac_ra": MAC.usrp2_node(4),"timestamp":time.time()} 
            
            valores_DATA12={"payload":"Paquete_que_llega12", "address1":MAC.usrp2_node(2),"address2":MAC.usrp2_node(1),"N_SEQ":N_SEQ, "N_FRAG":N_FRAG, "timestamp":time.time()}
            valores_DATA13={"payload":"Paquete_que_llega13", "address1":MAC.usrp2_node(3),"address2":MAC.usrp2_node(1),"N_SEQ":N_SEQ, "N_FRAG":N_FRAG, "timestamp":time.time()}
            valores_DATA14={"payload":"Paquete_que_llega14", "address1":MAC.usrp2_node(4),"address2":MAC.usrp2_node(1),"N_SEQ":N_SEQ, "N_FRAG":N_FRAG, "timestamp":time.time()}
            
            valores_DATA21={"payload":"Paquete_que_llega21", "address1":MAC.usrp2_node(1),"address2":MAC.usrp2_node(2),"N_SEQ":N_SEQ, "N_FRAG":N_FRAG, "timestamp":time.time()}
            valores_DATA23={"payload":"Paquete_que_llega23", "address1":MAC.usrp2_node(3),"address2":MAC.usrp2_node(2),"N_SEQ":N_SEQ, "N_FRAG":N_FRAG, "timestamp":time.time()}
            valores_DATA24={"payload":"Paquete_que_llega24", "address1":MAC.usrp2_node(4),"address2":MAC.usrp2_node(2),"N_SEQ":N_SEQ, "N_FRAG":N_FRAG, "timestamp":time.time()}
            
            valores_DATA31={"payload":"Paquete_que_llega31", "address1":MAC.usrp2_node(1),"address2":MAC.usrp2_node(3),"N_SEQ":N_SEQ, "N_FRAG":N_FRAG, "timestamp":time.time()}
            valores_DATA32={"payload":"Paquete_que_llega32", "address1":MAC.usrp2_node(2),"address2":MAC.usrp2_node(3),"N_SEQ":N_SEQ, "N_FRAG":N_FRAG, "timestamp":time.time()}
            valores_DATA34={"payload":"Paquete_que_llega34", "address1":MAC.usrp2_node(4),"address2":MAC.usrp2_node(3),"N_SEQ":N_SEQ, "N_FRAG":N_FRAG, "timestamp":time.time()}
            
            valores_DATA41={"payload":"Paquete_que_llega41", "address1":MAC.usrp2_node(1),"address2":MAC.usrp2_node(4),"N_SEQ":N_SEQ, "N_FRAG":N_FRAG, "timestamp":time.time()}
            valores_DATA42={"payload":"Paquete_que_llega42", "address1":MAC.usrp2_node(2),"address2":MAC.usrp2_node(4),"N_SEQ":N_SEQ, "N_FRAG":N_FRAG, "timestamp":time.time()}
            valores_DATA43={"payload":"Paquete_que_llega43", "address1":MAC.usrp2_node(3),"address2":MAC.usrp2_node(4),"N_SEQ":N_SEQ, "N_FRAG":N_FRAG, "timestamp":time.time()}
            
            valores_RTS12 = {"duration":0, "mac_ra":MAC.usrp2_node(2), "mac_ta":MAC.usrp2_node(1),"timestamp":time.time()}
            valores_RTS13 = {"duration":0, "mac_ra":MAC.usrp2_node(3), "mac_ta":MAC.usrp2_node(1),"timestamp":time.time()}
            valores_RTS14 = {"duration":0, "mac_ra":MAC.usrp2_node(4), "mac_ta":MAC.usrp2_node(1),"timestamp":time.time()}
            
            valores_RTS21 = {"duration":0, "mac_ra":MAC.usrp2_node(1), "mac_ta":MAC.usrp2_node(2),"timestamp":time.time()}
            valores_RTS23 = {"duration":0, "mac_ra":MAC.usrp2_node(3), "mac_ta":MAC.usrp2_node(2),"timestamp":time.time()}
            valores_RTS24 = {"duration":0, "mac_ra":MAC.usrp2_node(4), "mac_ta":MAC.usrp2_node(2),"timestamp":time.time()}
            
            valores_RTS31 = {"duration":0, "mac_ra":MAC.usrp2_node(1), "mac_ta":MAC.usrp2_node(3),"timestamp":time.time()}
            valores_RTS32 = {"duration":0, "mac_ra":MAC.usrp2_node(2), "mac_ta":MAC.usrp2_node(3),"timestamp":time.time()}
            valores_RTS34 = {"duration":0, "mac_ra":MAC.usrp2_node(4), "mac_ta":MAC.usrp2_node(3),"timestamp":time.time()}
            
            valores_RTS41 = {"duration":0, "mac_ra":MAC.usrp2_node(1), "mac_ta":MAC.usrp2_node(4),"timestamp":time.time()}
            valores_RTS42 = {"duration":0, "mac_ra":MAC.usrp2_node(2), "mac_ta":MAC.usrp2_node(4),"timestamp":time.time()}
            valores_RTS43 = {"duration":0, "mac_ra":MAC.usrp2_node(3), "mac_ta":MAC.usrp2_node(4),"timestamp":time.time()}
                    
            # Packet generation with the selected values
            # FIX ME! By default, coderate = "1", which means 6 Mbps
            paquete1=MAC.ftw_make("DATA",valores_DATA12,"1",4)      # valores_DATA12 means node 1 sends a Data packet to node 2
            paquete2=MAC.ftw_make("DATA",valores_DATA13,"1",4)
            paquete3=MAC.ftw_make("DATA",valores_DATA14,"1",4)
            paquete4=MAC.ftw_make("DATA",valores_DATA21,"1",4)
            paquete5=MAC.ftw_make("DATA",valores_DATA23,"1",4)
            paquete6=MAC.ftw_make("DATA",valores_DATA24,"1",4)
            paquete7=MAC.ftw_make("DATA",valores_DATA31,"1",4)
            paquete8=MAC.ftw_make("DATA",valores_DATA32,"1",4)
            paquete9=MAC.ftw_make("DATA",valores_DATA34,"1",4)
            paquete10=MAC.ftw_make("DATA",valores_DATA41,"1",4)
            paquete11=MAC.ftw_make("DATA",valores_DATA42,"1",4)
            paquete12=MAC.ftw_make("DATA",valores_DATA43,"1",4)
    
            paquete13=MAC.ftw_make("RTS",valores_RTS12,"1",4)       # valores_RTS12 means node 1 sends a RTS packet to node 2
            paquete14=MAC.ftw_make("RTS",valores_RTS13,"1",4)
            paquete15=MAC.ftw_make("RTS",valores_RTS14,"1",4)
            paquete16=MAC.ftw_make("RTS",valores_RTS21,"1",4)
            paquete16=MAC.ftw_make("RTS",valores_RTS23,"1",4)
            paquete17=MAC.ftw_make("RTS",valores_RTS24,"1",4)
            paquete18=MAC.ftw_make("RTS",valores_RTS31,"1",4)
            paquete19=MAC.ftw_make("RTS",valores_RTS32,"1",4)
            paquete20=MAC.ftw_make("RTS",valores_RTS34,"1",4)
            paquete21=MAC.ftw_make("RTS",valores_RTS41,"1",4)
            paquete22=MAC.ftw_make("RTS",valores_RTS42,"1",4)
            paquete23=MAC.ftw_make("RTS",valores_RTS43,"1",4)        
            
            paquete24=MAC.ftw_make("CTS",valores_CTS1,"1",4)        # valores_CTS1 means Receiver Addres = Node 1 MAC 
            paquete25=MAC.ftw_make("CTS",valores_CTS2,"1",4)
            paquete26=MAC.ftw_make("CTS",valores_CTS3,"1",4)
            paquete27=MAC.ftw_make("CTS",valores_CTS4,"1",4)
            
            paquete28=MAC.ftw_make("ACK",valores_ACK1,"1",4)        # valores_ACK1 means Receiver Addres = Node 1 MAC
            paquete29=MAC.ftw_make("ACK",valores_ACK2,"1",4)
            paquete30=MAC.ftw_make("ACK",valores_ACK3,"1",4)
            paquete31=MAC.ftw_make("ACK",valores_ACK4,"1",4)
            
            paquete32=MAC.ftw_make("BEACON",valores_B1,"1",4)       # valores_B1 means a BEACON generated by node 1
            paquete33=MAC.ftw_make("BEACON",valores_B2,"1",4)
            paquete34=MAC.ftw_make("BEACON",valores_B3,"1",4)
            paquete35=MAC.ftw_make("BEACON",valores_B4,"1",4)
            
            random.seed(time.time())
            
            # modify 'numero' in order to force the arrival of a selected packet to the PHY RX layer
            numero = random.randint(0,33)
            
            #DEBUG: used to test the correct RTS/CTS functionality   (MAC RX-side)
            #if n_packets == 1: numero = 12  
            #if n_packets == 2: numero = 24  
            #if n_packets == 3: numero = 0   
            #if n_packets == 4: numero = 28 
            
            #DEBUG: used to test the correct RTS/CTS functionality (MAC TX-side)
            #if n_packets == 1: numero = 15  
            #if n_packets == 2: numero = 23  
            #if n_packets == 3: numero = 3   
            #if n_packets == 4: numero = 27        
            
            # Select which type of frame is going to be generated 
            if numero == 0:
                pkt = crear_paquete("DATA",paquete1)
            elif numero == 1:
                pkt = crear_paquete("DATA",paquete2)
            elif numero == 2:
                pkt = crear_paquete("DATA",paquete3)
            elif numero == 3:
                pkt = crear_paquete("DATA",paquete4)
            elif numero == 4:
                pkt = crear_paquete("DATA",paquete5)
            elif numero == 5:
                pkt = crear_paquete("DATA",paquete6)
            elif numero == 6:
                pkt = crear_paquete("DATA",paquete7)
            elif numero == 7:
                pkt = crear_paquete("DATA",paquete8)
            elif numero == 8:
                pkt = crear_paquete("DATA",paquete9)
            elif numero == 9:
                pkt = crear_paquete("DATA",paquete10)
            elif numero == 10:
                pkt = crear_paquete("DATA",paquete11)
            elif numero == 11:
                pkt = crear_paquete("DATA",paquete12)
            elif numero == 12:
                pkt = crear_paquete("RTS",paquete13) 
            elif numero == 13:
                pkt = crear_paquete("RTS",paquete14) 
            elif numero == 14:
                pkt = crear_paquete("RTS",paquete15)
            elif numero == 15:
                pkt = crear_paquete("RTS",paquete16)
            elif numero == 16:
                pkt = crear_paquete("RTS",paquete17)
            elif numero == 17:
                pkt = crear_paquete("RTS",paquete18)
            elif numero == 18:
                pkt = crear_paquete("RTS",paquete19)
            elif numero == 19:
                pkt = crear_paquete("RTS",paquete20)
            elif numero == 20:
                pkt = crear_paquete("RTS",paquete21)
            elif numero == 21:
                pkt = crear_paquete("RTS",paquete22)
            elif numero == 22:
                pkt = crear_paquete("RTS",paquete23)
            elif numero == 23:
                pkt = crear_paquete("CTS",paquete24)
            elif numero == 24:
                pkt = crear_paquete("CTS",paquete25)
            elif numero == 25:
                pkt = crear_paquete("CTS",paquete26)
            elif numero == 26:
                pkt = crear_paquete("CTS",paquete27)
            elif numero == 27:
                pkt = crear_paquete("ACK",paquete28)
            elif numero == 28:
                pkt = crear_paquete("ACK",paquete29)
            elif numero == 29:
                pkt = crear_paquete("ACK",paquete30)
            elif numero == 30:
                pkt = crear_paquete("ACK",paquete31)
            elif numero == 31:
                if MAC.usrp2_node(options.node) == MAC.usrp2_node(1):
                    pkt = crear_paquete("OTHER",[])
                else:
                    pkt = crear_paquete("BEACON",paquete32)
            elif numero == 32:
                if MAC.usrp2_node(options.node) == MAC.usrp2_node(2):
                    pkt = crear_paquete("OTHER",[])
                else:
                    pkt = crear_paquete("BEACON",paquete33)
            elif numero == 33:
                if MAC.usrp2_node(options.node) == MAC.usrp2_node(3):
                    pkt = crear_paquete("OTHER",[])
                else:
                    pkt = crear_paquete("BEACON",paquete34)
            elif numero == 34:
                if MAC.usrp2_node(options.node) == MAC.usrp2_node(4):
                    pkt = crear_paquete("OTHER",[])
                else:
                    pkt = crear_paquete("BEACON",paquete35)
            elif numero >35:
                pkt = crear_paquete("OTHER",[])
                n_packets -= 1
            #n_packets += 1
            
            paquete = pickle.dumps(pkt,1)
            s.send(paquete)
            s.close()
            time.sleep(0.1)    # Packet arrival interval