Best Python code snippet using playwright-python
uwicore_80211mac.py
Source:uwicore_80211mac.py
1#!/usr/bin/env python2# Copyright 2005, 2006 Free Software Foundation, Inc.3 4# This file is part of GNU Radio5 6# GNU Radio is free software; you can redistribute it and/or modify7# it under the terms of the GNU General Public License as published by8# the Free Software Foundation; either version 3, or (at your option)9# any later version.10 11# GNU Radio is distributed in the hope that it will be useful,12# but WITHOUT ANY WARRANTY; without even the implied warranty of13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the14# GNU General Public License for more details.15 16# You should have received a copy of the GNU General Public License17# along with GNU Radio; see the file COPYING. If not, write to18# the Free Software Foundation, Inc., 51 Franklin Street,19# Boston, MA 02110-1301, USA.202122# Projectname: uwicore@umh_80211_MAC2324# Filename: uwicore_80211mac.py2526# This script contains the MAC Finite State Machine (FSM) implementation developed by the Uwicore 27# Laboratory at the University Miguel Hernandez of Elche. More detailed information about the 28# FSM diagram transitions can be found at www.uwicore.umh.es/mhop-testbeds.html or at the publication:2930# J.R. Gutierrez-Agullo, B. Coll-Perales and J. Gozalvez, "An IEEE 802.11 MAC Software Defined Radio Implementation for Experimental Wireless Communications and Networking Research", Proceedings of the 2010 IFIP/IEEE Wireless Days (WD'10), pp. 1-5, 20-22 October 2010, Venice (Italy).3132# Ubiquitous Wireless Communications Research Laboratory 33# Uwicore, http://www.uwicore.umh.es34# Communications Engineering Department35# University Miguel Hernandez of Elche36# Avda de la Universidad, s/n37# 03202 Elche, Spain38# Release: April 201139# List of Authors:40# Juan R. Gutierrez-Agullo (jgutierrez@umh.es)41# Baldomero Coll-Perales (bcoll@umh.es)42# Dr. Javier Gozalvez (j.gozalvez@umh.es)434445from optparse import OptionParser46from gnuradio.eng_option import eng_option47import uwicore_mac_utils as MAC4849import time, sys, random5051# Finite State Machine MAC main52def main():53 parser = OptionParser(option_class=eng_option, conflict_handler="resolve")54 parser.add_option("", "--PHYport", type="intx", default=8013,55 help="PHY communication socket port, [default=%default]")56 parser.add_option("", "--MACport", type="intx", default=8001,57 help="MAC communication socket port, [default=%default]")58 parser.add_option("-i", "--interp", type="intx", default=10,59 help="USRP2 interpolation factor value, [default=%default]\60 5 -> 802.11a/g, OFDM T_Symbol=4us, \61 10 -> 802.11p, OFDM T_Symbol=8us")62 parser.add_option("", "--regime", type="string", default="1",63 help="OFDM regimecode [default=%default]\64 1 -> 6 (3) Mbit/s (BPSK r=0.5), \65 2 -> 9 (4.5) Mbit/s (BPSK r=0.75), \66 3 -> 12 (6) Mbit/s (QPSK r=0.5), \67 4 -> 18 (9) Mbit/s (QPSK r=0.75), \68 5 -> 24 (12) Mbit/s (QAM16 r=0.5), \69 6 -> 36 (18) Mbit/s (QAM16 r=0.75), \70 7 -> 48 (24) Mbit/s (QAM64 r=0.66), \71 8 -> 54 (27) Mbit/s (QAM64 r=0.75)")72 parser.add_option("-n", "--node", type="intx", default=1,73 help="Number of USRP2 node, [default=%default]")74 parser.add_option("", "--beta", type="float", default=10000,75 help="Scaling Time Parameter, [default=%default]")76 parser.add_option("-t", "--time_slot", type="float", default=9e-6,77 help="Time slot value, [default=%default]")78 parser.add_option("-B", "--BI", type="float", default=1,79 help="Beacon Interval (BI) value in seconds, [default=%default]")80 parser.add_option("-S", "--SIFS", type="float", default=16e-6,81 help="Short Inter-frame space (SIFS) value, [default=%default]")82 parser.add_option('', "--retx", action="store_true", default=False,83 help="Retransmissions enabled, [default=%default]")84 parser.add_option('', "--RTS", action="store_true", default=False,85 help="RTS-threshold enabled, [default=%default]")86 parser.add_option('-v', "--V", action="store_true", default=False,87 help="Print debug information, [default=%default]")88 (options, args) = parser.parse_args ()89 90 my_mac = MAC.usrp2_node(options.node) # MAC address for this node91 dest_mac = MAC.usrp2_node(2) # Dummy value (updated when an incoming packet arrives)92 93 """94 IEEE 802.11-a MAC parameters95 """96 beta = options.beta # scaling time parameter97 tslot = options.time_slot * beta98 SIFS = options.SIFS * beta99 DIFS = SIFS + 2 * tslot100 Preamble = DIFS #16e-6101 PLCP_header = 4e-6 * beta102 ACK_time = Preamble + PLCP_header103 CW_min = 15104 CW_max = 1023105 RTS_THRESHOLD = 150106 dot11FragmentationTh = 1036107108 # TX time estimation for a CTS and an ACK packet109 empty_values = {"duration":0, "mac_ra":my_mac, "timestamp":time.time()} 110 CTS_empty = MAC.generate_pkt("CTS", options.interp, options.regime, empty_values)111 T_cts = CTS_empty["INFO"]["txtime"]112 ACK_empty = MAC.generate_pkt("ACK", options.interp, options.regime, empty_values)113 T_ack = ACK_empty["INFO"]["txtime"]114 115 # Set socket ports116 PHY_port = options.PHYport117 #PHYRX_port = options.PHYRXport118 MAC_port = options.MACport119 120 # Variables involving MAC tests121 testing = False # Testing mode active, used to conduct trials122 N_TESTS = 1000 # Number of tests123 N_TESTS_INI = N_TESTS 124 LONG_TESTS = 20 # Payload length for tests125 payload_test = "0000" + LONG_TESTS*'1' # Payload for tests126 test_with_sensing = True # Carrier Sensing (CS) allowed during the test127 total_processing_time = 0 # Total processing time128 t_sense_mean = 0 # CS average time129 t_csense = 0 # CS time130 t_MAC = 0 # MAC time131 t_MAC_mean = 0 # MAC average time132 packet_i=0 # Packets sent counter133 n_sensing = 0 # Number of CS performed134 135 # 'State' controls the state of the MAC136 State = "IDLE" 137 138 # Initial Conditions of the Finite State Machine139 NAV = 0 # Network Allocation Vector 140 N_RETRIES = 0 # Retries to send a packet counter141 busy_in_wfd = False # Busy in Wait_for_DIFS state142 BO_frozen = "NO" # Backoff frozen 143 TX_attempts = 0 # Tries to send a packet counter144 CTS_failed = False # CTS reception failed145 chan = "FREE" # Channel state = IDDLE146 N_SEQ = 0 # Sequence number counter147 N_FRAG = 0 # Fragment number counter148 first_tx = True # Is the first attempt to send a packet?149 frag_count = 0 # Counter used during fragmentation150 data_temp_reass = "" # Initial variable to perform de re-assembly process151 verbose = True # Shows when the MAC is in 'IDDLE' state152 beaconing = False # Is ON the Beaconing process?153 fragmenting = 0 # Is the packet received a fragment?154 155 if options.V:156 print "============================================="157 print " \t MAC layer: DCF + RTS/CTS"158 print "============================================="159 print "MAC address:",MAC.which_dir(my_mac)160 print "Rate = ",options.regime161 print "tslot(s): %f \t SIFS(s): %f"%(tslot,SIFS)162 print "DIFS(s): %f \t T_ACK(s): %f"%(DIFS, ACK_time)163 print "pseudo-random exp. BACKOFF [%i,%i]"%(CW_min, CW_max)164 if options.RTS: 165 print "RTS/CTS: enabled"166 print "\t with RTS Threshold(Bytes): %i \t" %RTS_THRESHOLD167 else: print "RTS/CTS: disabled"168 print "Fragmentation Threshold (Bytes):",dot11FragmentationTh169 if options.retx: print "Retransmissions: enabled"170 else: print "Retransmissions: disabled"171 print "Scaling time parameter = ",beta172 print "============================================="173 174 """175 Starts the MAC operation176 """177 while 1:178 #IDLE STATE179 if State == "IDLE":180 # Is a RTS?181 reply_phy1, packet_phy1 = MAC.read_phy_response(PHY_port, "RTS")182 #print State183 if reply_phy1 == "YES":184 verbose = True # Show when the MAC is IDLE185 copied = packet_phy1 # Copy the received packet from the PHY186 x = copied["INFO"] # Copy the 802.11 frame included in the received packet from PHY187 if my_mac == x["RX_add"]:188 print "[R]-[%s]-[DA: %s]-[SA: %s]-[duration: %f]-[IFM:1]" %(copied["HEADER"],MAC.which_dir(x["RX_add"]),MAC.which_dir(x["TX_add"]),x["txtime"])189 dest_mac = (x["TX_add"]) # Receiver Address of the CTS frame190 RTS_duration = x["txtime"] # Value of RTS' TX time 191 if options.V: print "| IDLE | RTS received | TRANSMITTING_CTS |" 192 """193 #============================================================194 # /TEST/ UNCOMMENT TO CHECK RTS/CTS FUNCTIONALITY195 #============================================================196 # STEP 1/4: Node 1 --> RTS197 values = {"duration":x["txtime"], "mac_ra":x["RX_add"], "mac_ta":x["TX_add"], "timestamp":time.time()} 198 RTS_forced = MAC.generate_pkt("RTS", options.interp, options.regime, values)199 packet_RTS_forced = MAC.create_packet("PKT", RTS_forced)200 MAC.transmit(packet_RTS_forced, PHY_port)201 time.sleep(tslot)202 #============================================================203 """204 State = "TRANSMITTING_CTS"205 else:206 print "[R]-[%s]-[DA:%s]-[SA:%s]-[duration:%f]-[IFM:0]" %(copied["HEADER"],MAC.which_dir(x["RX_add"]),MAC.which_dir(x["TX_add"]),x["txtime"]) 207 tiempo = x["txtime"] / (1.0e3) # Divided by 1e3 because txtime is on milliseconds208 if options.V: print "| IDLE | RTS captured (update NAV) | IDLE |"209 NAV = MAC.update_NAV(time.time(), tiempo, tslot)210 State = "IDLE"211 212 # Check upper layer buffer for data to send213 else:214 reply_up, PAYLOAD = MAC.read_ul_buffer(MAC_port)215 if reply_up == "YES":216 verbose = True217 if options.V: print "| IDLE | MAC has DATA to Tx | WAIT_FOR_NAV |"218 State = "WAIT_FOR_NAV"219 elif reply_up == "BEACON":220 beaconing = True221 if options.V: print "| IDLE | Transmit BEACON FRAME | WAIT_FOR_NAV |"222 State = "TRANSMITTING_RTS"223 elif reply_up == "NO": 224 # is a CTS? 225 reply_phy2, packet_phy2 = MAC.read_phy_response(PHY_port, "CTS")226 if reply_phy2 == "YES":227 verbose = True228 copied = packet_phy2229 x = copied["INFO"]230 print "[R]-[%s]-[DA:%s]-[duration:%f]-[IFM:0]" %(copied["HEADER"],MAC.which_dir(x["RX_add"]),x["txtime"])231 tiempo = x["txtime"]/1.0e3 232 if options.V: print "| IDLE | CTS captured (update NAV) | IDLE |"233 NAV = MAC.update_NAV(time.time(), tiempo, tslot)234 State = "IDLE"235 else:236 if verbose == True: 237 print "\n| IDLE |\n"238 verbose = False239 State = "IDLE"240 if testing == True: # if True, it allows to switch manually to any state 241 t_testA = time.time() 242 packet_i +=1243 State = "WAIT_FOR_NAV" # Edit the state to switch to 244 245 if State == "IDLE": time.sleep(tslot) # Time-slotted MAC246 247 248 #WAIT_FOR_NAV STATE249 elif State == "WAIT_FOR_NAV":250 #print State251 NAV = MAC.update_NAV(time.time(), NAV, tslot)252 if NAV > 0:253 if options.V: print "| WAIT_FOR_NAV | NAV > 0 | WAIT_FOR_NAV |"254 State = "WAIT_FOR_NAV"255 else:256 if options.V: print "| WAIT_FOR_NAV | NAV = 0 | WAIT_FOR_DIFS |"257 State = "WAIT_FOR_DIFS"258 chan = "FREE"259 260 #WAIT_FOR_DIFS STATE261 elif State == "WAIT_FOR_DIFS":262 # This state performs the channel sensing process and decides whether the channel is BUSY or IDLE263 #print State264 t_inicial=time.time()265 t_final=t_inicial + DIFS266 n_sensing=0267 while n_sensing < 2:268 t_testB = time.time()269 channel_in_wfd, t = MAC.sense_channel(PHY_port)270 t_testC = time.time()271 assert (tslot - (t_testC-t_testB) >=0),"Timing Error. Please increase the beta parameter."272 time.sleep(tslot-(t_testC-t_testB))273 if channel_in_wfd == "OCCUPIED":274 chan = "OCCUPIED"275 t_csense = t_csense + (t_testC - t_testB)276 n_sensing +=1 277 assert (t_final - time.time() >=0),"Timing Error. Please increase the beta parameter."278 time.sleep(t_final - time.time())279 t_csense = t_csense/3280 # print "Wait_for_DIFS operation time = ", (time.time()-t_inicial) # DEBUG281 282 if chan == "FREE":283 if BO_frozen == "NO" and busy_in_wfd == False and CTS_failed == False:284 BACKOFF = 0 # Channel IDLE for the first time, BOtimer = 0285 State = "BACKING_OFF"286 if options.V: print "| WAIT_FOR_DIFS | Channel idle | BACKING_OFF |" 287 else:288 if BO_frozen == "NO" and CTS_failed == False: # If it is the 1st time, set the CW289 BACKOFF = MAC.retry(TX_attempts, CW_min)290 TX_attempts = TX_attempts + 1291 #BO_frozen=="YES"292 BO_first_time = 1293 State = "IDLE"294 chan = "FREE"295 if options.V: print "| WAIT_FOR_DIFS | Channel busy | IDLE |"296 297 298 #BACKING_OFF STATE299 elif State == "BACKING_OFF":300 #print State301 busy_in_wfd = False302 if BACKOFF == 0:303 BO_first_time = 1304 State = "TRANSMITTING_RTS"305 else:306 tx = time.time() 307 canal_en_bo, t = MAC.sense_channel(PHY_port)308 309 if canal_en_bo == "FREE": # Channel idle310 BACKOFF = BACKOFF - 1311 BO_first_time = 0 # Backoff process started, freeze CW value!312 if BACKOFF > 0: 313 if options.V: print "| BACKING_OFF | Channel idle (CW = %i) | BACKING_OFF |"%BACKOFF314 State = "BACKING_OFF"315 else:316 if options.V: print "| BACKING_OFF | Channel idle (CW = %i) | TRANSMITTING_RTS |"%BACKOFF 317 State = "TRANSMITTING_RTS"318 busy_in_wfd = False319 320 else: # Channel busy321 BACKOFF = BACKOFF - 1322 BO_first_time = 0 # Channel busy, CW frozen323 BO_frozen = "YES"324 State = "IDLE"325 if options.V:326 if options.V: print "| BACKING_OFF | Channel busy (CW = %i) | IDLE |"%BACKOFF 327 ty = time.time()328 assert (tslot - (ty - tx) >=0),"Timing Error. Please increase the beta parameter."329 time.sleep(tslot - (ty - tx))330 331 #TRANSMITTING_RTS STATE332 elif State == "TRANSMITTING_RTS":333 #print State334 #TX_attempts = 0 # DEBUG335 BO_first_time = 1 # Update backoff status for the next time336 337 # Work out TX time of the packet to send338 if testing == True:339 N_TESTS -= 1340 N_SEQ +=1 341 values = {"payload":payload_test, "address1":dest_mac, "address2":my_mac, "N_SEQ":N_SEQ, "N_FRAG":0,"timestamp":time.time()}342 test = MAC.generate_pkt("DATA", options.interp, options.regime, values)343 packet_TEST = MAC.create_packet("PKT", test)344 t_testD = time.time()345 346 # Send the packet to PHY347 MAC.transmit(packet_TEST, PHY_port)348 349 t_MAC = t_MAC + (t_testD-t_testA)350 t_MAC_mean = t_MAC/packet_i351 t_sense_mean = t_sense_mean + t_csense352 print "=============== Packet %i ==================="%(packet_i)353 print "MAC processing time = ",(t_testD-t_testA)354 print "MAC processing time (average) = ", t_MAC_mean355 print "Carrier sensing time = ",(t_testC - t_testB)356 print "Carrier sensing time (average) = ",t_sense_mean/packet_i357 print "============================================="358 359 if N_TESTS == 0: 360 sys.stderr.write("End of Test. Press ENTER to exit")361 z=raw_input()362 sys.exit(0)363 364 # Not a Beacon to TX365 elif beaconing == False: 366 values = {"payload":PAYLOAD, "address1":dest_mac, "address2":my_mac, "N_SEQ":N_SEQ, "N_FRAG":N_FRAG, "timestamp":time.time()}367 packet = MAC.generate_pkt("DATA", options.interp, options.regime, values)368 T_data = packet["INFO"]["txtime"]369 '''370 Value of RTS fields:371 Duration = T_cts + T_ack + 3*SIFS + T_data372 mac_ra = dest_mac373 mac_ta = my_mac374 '''375 if options.RTS == True:376 if PAYLOAD > RTS_THRESHOLD:377 if first_tx == True: 378 retx_retries = 7379 fail_tx = False380 first_tx = False381 duration = (3 * SIFS) + (T_cts + T_ack + T_data) / 1000 #Txtime in milliseconds382 mac_ra = dest_mac383 mac_ta = my_mac384 values = {"duration":duration, "mac_ra":mac_ra, "mac_ta":mac_ta,"timestamp":time.time()} 385 RTS = MAC.generate_pkt("RTS", options.interp, options.regime, values)386 packet_RTS = MAC.create_packet("PKT", RTS)387 MAC.transmit(packet_RTS, PHY_port)388 print "[T]-[RTS]-[SA:%s]-[DA=%s]-[duration:%i]" %(MAC.which_dir(my_mac),MAC.which_dir(mac_ta),duration)389 WFC_first_time = 1 # First time in WAITING_FOR_CTS state390 State = "WAITING_FOR_CTS"391 if options.V: print "| TRANSMITTING_RTS | (PAYLOAD > RTS_Th) Send RTS | WAITING_FOR_CTS |"392 else:393 if first_tx == True: 394 retx_retries = 4395 fail_tx = False396 first_tx = False397 State = "TRANSMITTING_UNICAST"398 if options.V: print "| TRANSMITTING_RTS | (PAYLOAD < RTS_Th) Send DATA | TRANSMITTING_UNICAST |"399 else:400 if first_tx == True: 401 retx_retries = 4402 fail_tx = False403 first_tx = False404 if options.V: print "| TRANSMITTING_RTS | (RTS OFF) Send DATA | TRANSMITTING_UNICAST |"405 State = "TRANSMITTING_UNICAST"406 else:407 values = {"address2":my_mac, "N_SEQ":N_SEQ,"N_FRAG":0 ,"BI":options.BI, "timestamp":time.time()}408 print "[T]-[BEACON]-[SA:%s]-[BI=%f]-[#seq:%i]" %(MAC.which_dir(my_mac),options.BI,N_SEQ)409 if options.V: print "| TRANSMITTING_RTS | Send BEACON | IDLE |"410 BEACON = MAC.generate_pkt("BEACON", options.interp, options.regime, values)411 packet_BEACON = MAC.create_packet("PKT", BEACON)412 MAC.transmit(packet_BEACON, PHY_port)413 MAC.remove_ul_buff_packet(MAC_port)414 N_SEQ += 1415 beaconing = False416 verbose = True417 State = "IDLE"418 419 #TRANSMITTING_UNICAST STATE420 elif State == "TRANSMITTING_UNICAST":421 '''422 Send packet to PHY for its transmission using the USRP2423 packet = [MPDU][LENGHT][INFO] 424 pkt = [Header: PKT][Data: packet]425 '''426 #print State427 #if options.V: print "[%s]\t: TX DATA packet to PHY" % State428 if len(PAYLOAD) > dot11FragmentationTh:429 if options.V: print "| TRANSMITTING_UNICAST | Send Fragmented Data | TRANSMITTING_FRAGMENTED_PACKET |"430 State = "TRANSMITTING_FRAGMENTED_PACKET"431 first_time_fg = True432 WF_ACK_FG_first_time = True433 else:434 values = {"payload":PAYLOAD, "address1":dest_mac, "address2":my_mac, "N_SEQ":N_SEQ, "N_FRAG":N_FRAG, "timestamp":time.time()}435 print "[T]-[DATA]-[DA:%s]-[SA:%s]-[MF:0]-[#seq:%i]-[Payload = %s]" %(MAC.which_dir(dest_mac),MAC.which_dir(my_mac),N_SEQ,PAYLOAD)436 if options.V: print "| TRANSMITTING_UNICAST | Send DATA | WAITING_FOR_ACK |"437 N_SEQ += 1438 N_FRAG = 0439 if fail_tx == False:440 packet = MAC.generate_pkt("DATA", options.interp, options.regime, values)441 else:442 packet = MAC.generate_pkt("DATA_RETX", options.interp, options.regime, values)443 pkt = MAC.create_packet("PKT", packet)444 MAC.transmit(pkt, PHY_port)445 WF_ACK_first_time = 1 # First time in WAITING_FOR_ACK state 446 State = "WAITING_FOR_ACK"447 448 # WAITING_FOR_CTS STATE449 elif State == "WAITING_FOR_CTS":450 #print State451 if WFC_first_time == 1:452 CTS_time = SIFS453 CTS_fin = 0 454 t0 = time.time()455 no_packet, packet_phy = MAC.read_phy_response(PHY_port, "CTS")456 457 '''458 #============================================================459 # /TEST/ UNCOMMENT TO CHECK RTS/CTS FUNCTIONALITY460 #============================================================461 # STEP 2/4: Node 2 --> CTS462 mac_ra = my_mac463 values = {"duration":0, "mac_ra":mac_ra,"timestamp":time.time()} 464 CTS_forced = MAC.generate_pkt("CTS", options.interp, options.regime, values)465 packet_CTS_forced = MAC.create_packet("PKT", CTS_forced)466 MAC.transmit(packet_CTS_forced, PHY_port)467 time.sleep(tslot)468 #============================================================469 '''470 if no_packet == "YES":471 # Is the CTS frame for this station? 472 copied = packet_phy["INFO"]473 if copied["RX_add"] == my_mac:474 WFC_first_time = 1475 State = "TRANSMITTING_UNICAST"476 CTS_fin = 1477 TX_attempts = 0478 CTS_failed = False479 if options.V:480 print "[R]-[CTS]-[RA: %s]-[duration: %f]-[IFM:1]" %(MAC.which_dir(copied["RX_add"]),copied["txtime"])481 if options.V: print "| WAITING_FOR_CTS | CTS received | TRANSMITTING_UNICAST |" 482 else:483 CTS_fin = 1 # CTS captured! Transmission aborted to avoid a collision484 print "[R]-[CTS]-[RA:%s]-[duration:%f]-[IFM:0]" %(MAC.which_dir(copied["RX_add"]),copied["txtime"])485 State = "IDLE"486 nuevo_NAV = copied["txtime"]/1e3487 NAV = MAC.update_NAV(time.time(),nuevo_NAV , tslot)488 if options.V: print "| WAITING_FOR_CTS | CTS captured (Update NAV = %f) | IDLE |"%NAV489490 else:491 State = "WAITING_FOR_CTS" 492 WFC_first_time = 0 493 #CTS_fin = 0494 t1 = time.time()495 CTS_time = CTS_time - (t1 - t0)496 497 if CTS_fin == 0:498 if CTS_time > 0:499 State = "WAITING_FOR_CTS" 500 else:501 TX_attempts = TX_attempts + 1502 BACKOFF = MAC.retry(TX_attempts, CW_min)503 State = "IDLE" # Timer expired and CTS hasn't been received504 if options.V:505 if options.V: print "| WAITING_FOR_CTS | CTS not received | IDLE |"506 CTS_failed = True507 508509 #TRANSMITTING_FRAGMENTED_PACKET STATE510 elif State == "TRANSMITTING_FRAGMENTED_PACKET":511 #print State512 if first_time_fg == True:513 fragments = MAC.fragment(PAYLOAD, dot11FragmentationTh) #fragment the PAYLOAD based on a fragmentation threshold514 first_time_fg = False515 else:516 if len(fragments) > 1:517 payload_tmp = fragments[0]518 #Create packet with MORE FRAGMENT = 1 and payload = payload_tmp519 values = {"payload":payload_tmp, "address1":dest_mac, "address2":my_mac, "N_SEQ":N_SEQ, "N_FRAG":N_FRAG, "timestamp":time.time()}520 packet = MAC.generate_pkt("DATA_FRAG", options.interp, options.regime, values)521 N_SEQ += 1522 N_FRAG += 1523 pkt = MAC.create_packet("PKT", packet) 524 print "[T]-[FRAGMENTED DATA]-[DA:%s]-[SA:%s]-[MF:1]-[#seq:%i]-[#frag:%i]-[Payload = %s]" %(MAC.which_dir(dest_mac),MAC.which_dir(my_mac),N_SEQ,N_FRAG,payload_tmp)525 if options.V: print "| TRANSMITTING_FRAGMENTED_PACKET | Send DATA FRAG | WAIT_ACK_FRAGMENTED |"526 MAC.transmit(pkt, PHY_port)527 fragments.pop(0) #FIXME Retransmission for Fragmented packets is required528 fin_wait_ack_fragmented = False529 State = "WAIT_ACK_FRAGMENTED"530 elif len(fragments) == 1:531 payload_tmp = fragments[0]532 #Create packet with MORE FRAGMENT = 0 and payload = payload_tmp533 values = {"payload":payload_tmp, "address1":dest_mac, "address2":my_mac, "N_SEQ":N_SEQ, "N_FRAG":N_FRAG, "timestamp":time.time()}534 N_SEQ += 1535 N_FRAG += 1536 N_FRAG = 0537 print "[T]-[DATA]-[DA:%s]-[SA:%s]-[MF:0]-[#seq:%i]-[Payload = %s]" %(MAC.which_dir(dest_mac),MAC.which_dir(my_mac),N_SEQ, payload_tmp)538 if options.V: print "| TRANSMITTING_FRAGMENTED_PACKET | Send DATA FRAG (last fragment) | WAIT_ACK_FRAGMENTED |"539 packet = MAC.generate_pkt("DATA", options.interp, options.regime, values) 540 pkt = MAC.create_packet("PKT", packet) 541 MAC.transmit(pkt, PHY_port)542 fin_wait_ack_fragmented = True543 State = "WAIT_ACK_FRAGMENTED" 544545 #WAIT_ACK_FRAGMENTED STATE 546 elif State == "WAIT_ACK_FRAGMENTED":547 #print State548 if WF_ACK_FG_first_time == 1:549 T_ACK = SIFS550 ta1 = time.time()551 no_packet, packet_phy = MAC.read_phy_response(PHY_port, "ACK")552 if no_packet == "YES": # ACK addressed to this station553 x = packet_phy["INFO"]554 print "[R]-[%s]-[DA: %s]-[duration:%f]-[IFM:1]" %(packet_phy["HEADER"],MAC.which_dir(x["RX_add"]),x["txtime"])555 if fin_wait_ack_fragmented == True: # Last fragment sent556 if options.V: print "| WAIT_ACK_FRAGMENTED | All fragments acknowledged | IDLE |"557 State = "IDLE"558 MAC.remove_ul_buff_packet(MAC_port) # Remove the packet from upper layers559 first_tx = True560 else:561 print "[R]-[%s]-[DA:%s]-[duration:%f]-[IFM:1]" %(packet_phy["HEADER"],MAC.which_dir(x["RX_add"]),x["txtime"])562 if options.V: print "| WAIT_ACK_FRAGMENTED | ACK received | TRANSMITTING_FRAGMENTED_PACKET |"563 State = "TRANSMITTING_FRAGMENTED_PACKET"564 BACKOFF = 0565 WF_ACK_FG_first_time = 1566 ACK_FG_fin = 1 567 else:568 State = "WAIT_ACK_FRAGMENTED" # Not an ACK569 WF_ACK_FG_first_time = 0570 ACK_FG_fin = 0571 ta2=time.time()572 573 assert (tslot - (ta2 - ta1) >=0),"Timing Error. Please increase the beta parameter."574 time.sleep(tslot - (ta2 - ta1))575 tb = time.time()576 T_ACK = T_ACK - (tb - ta1)577 if ACK_FG_fin == 0:578 if T_ACK > 0:579 if options.V: print "| WAIT_ACK_FRAGMENTED | ACK not received yet | WAIT_ACK_FRAGMENTED |"580 State = "WAIT_ACK_FRAGMENTED"581 else: 582 if options.V: print "| WAIT_ACK_FRAGMENTED | ACK not received | IDLE |"583 State = "IDLE"584 MAC.remove_ul_buff_packet(MAC_port) # ACK not received within the Waiting_for_ack interval585 first_tx = True586 587588 #WAITING_FOR_ACK STATE 589 elif State == "WAITING_FOR_ACK":590 #print State591 if WF_ACK_first_time == 1:592 T_ACK = SIFS593 ta = time.time()594 no_packet, packet_phy = MAC.read_phy_response(PHY_port, "ACK")595 if no_packet == "YES":596 x = packet_phy["INFO"] 597 print "[R]-[%s]-[DA:%s]-[duration:%f]-[IFM:1]" %(packet_phy["HEADER"],MAC.which_dir(x["RX_add"]),x["txtime"])598 '''599 #============================================================600 # /TEST/ UNCOMMENT TO CHECK RTS/CTS FUNCTIONALITY601 #============================================================602 # STEP 4/4: Node 2 --> ACK603 mac_ra = my_mac604 values = {"duration":x["txtime"], "mac_ra":mac_ra,"timestamp":time.time()} 605 ACK_forced = MAC.generate_pkt("ACK", options.interp, options.regime, values)606 packet_ACK_forced = MAC.create_packet("PKT", ACK_forced)607 MAC.transmit(packet_ACK_forced, PHY_port)608 time.sleep(tslot)609 #============================================================610 '''611 if options.V: print "| WAITING_FOR_ACK | ACK received | IDLE |"612 State = "IDLE"613 BACKOFF = 0614 WF_ACK_first_time = 1615 ACK_fin = 1 616 MAC.remove_ul_buff_packet(MAC_port) # Packet acknoweledged, remove from upper layers617 first_tx = True618 619 else:620 State = "WAITING_FOR_ACK" # Not an ACK621 WF_ACK_first_time = 0622 ACK_fin = 0623 624 ta_fin = time.time()625 assert (tslot - (ta_fin - ta) >=0),"Timing Error. Please increase the beta parameter."626 time.sleep(tslot - (ta_fin - ta))627 tb = time.time()628 T_ACK = T_ACK - (tb - ta)629 if ACK_fin == 0:630 if T_ACK > 0:631 if options.V: print "| WAITING_FOR_ACK | ACK not received yet | WAITING_FOR_ACK |"632 State = "WAITING_FOR_ACK"633 else:634 # Not ACK yet, Reset CW to CWmin and go to IDLE635 if options.retx == True:636 retx_retries = retx_retries - 1637 if retx_retries < 0:638 CW = CW_min 639 State = "IDLE"640 MAC.remove_ul_buff_packet(MAC_port)641 first_tx = True642 if options.V: print "| WAITING_FOR_ACK | Remove packet from upper layers | IDLE |"643 N_FRAG = 0 644 fail_tx = False645 else:646 if options.V: print "| WAITING_FOR_ACK | ACK not received (retries left = %i) | IDLE |"%retx_retries647 State = "IDLE"648 fail_tx = True649 else: 650 State = "IDLE"651 if options.V: print "| WAITING_FOR_ACK | Remove packet from upper layers | IDLE |"652 MAC.remove_ul_buff_packet(MAC_port) # No Re-TX!653 first_tx = True654 655 #TRANSMITTING_CTS STATE 656 elif State == "TRANSMITTING_CTS":657 '''658 RTS received. NAV allows channel access.659 Send CTS to PHY for its transmission.660 - packet = [CTS][LENGHT][INFO]661 - pkt = [Header: PKT][Data: packet]662 '''663 #print State664 NAV = MAC.update_NAV(time.time(), NAV, tslot)665 if NAV > 0:666 if options.V: print "| TRANSMITTING_CTS | NAV > 0 | TRANSMITTING_CTS |"667 State = "TRANSMITTING_CTS"668 else:669 duration = RTS_duration - (2 * T_cts) / 10 - SIFS 670 mac_ra = dest_mac671 values = {"duration":duration, "mac_ra":mac_ra, "timestamp":time.time()} 672 CTS = MAC.generate_pkt("CTS", options.interp, options.regime, values)673 packet_CTS = MAC.create_packet("PKT", CTS)674 print "[T]-[CTS]-[DA:%s]-[duration=%f]" %(MAC.which_dir(mac_ra),duration)675 if options.V: print "| TRANSMITTING_CTS | CTS sent | WAITING_FOR_DATA |"676 MAC.transmit(packet_CTS, PHY_port)677 WF_DATA_first_time = 1678 State = "WAITING_FOR_DATA"679 680 #WAITING_FOR_DATA STATE 681 elif State == "WAITING_FOR_DATA":682 '''683 Once the CTS is transmitted, wait for Data arrival684 -> If a data packet arrives, go to TRANSMITTING_ACK685 -> If no, go to IDLE686 '''687 #print State688 if WF_DATA_first_time == 1:689 T_DATA = SIFS690 t_1 = time.time()691 no_packet, packet_phy = MAC.read_phy_response(PHY_port, "DATA")692 if no_packet == "YES":693 x = packet_phy["INFO"] # DATA packet addressed to this station694 '''695 #============================================================696 # /TEST/ UNCOMMENT TO CHECK RTS/CTS FUNCTIONALITY697 #============================================================698 # STEP 3/4: Node 1 --> DATA699 values = {"payload":"Paquete_que_llega12", "address1":x["mac_add1"], "address2":x["mac_add2"], "N_SEQ":N_SEQ, "N_FRAG":0, "timestamp":time.time()} 700 DATA_forced = MAC.generate_pkt("DATA", options.interp, options.regime, values)701 packet_DATA_forced = MAC.create_packet("PKT", DATA_forced)702 MAC.transmit(packet_DATA_forced, PHY_port)703 time.sleep(2*tslot)704 #============================================================705 '''706 dest_mac = x["mac_add2"]707 if x["MF"]==0: #More Fragments = 0708 if fragmenting == 0: # Not a fragmented packet709 print "[R]-[DATA]-[DA:%s]-[SA:%s]-[MF:0]-[IFM:1]-[PAYLOAD = %s]" %(MAC.which_dir(x["mac_add1"]),MAC.which_dir(x["mac_add2"]),x["PAYLOAD"])710 if options.V: print "| WAITING_FOR_DATA | DATA received | TRANSMITTING_ACK |"711 State = "TRANSMITTING_ACK"712 WF_DATA_first_time = 1 713 DATA_ok = 1714 frag_count = 0715 MAC.send_ul_buff_packet(MAC_port, x["PAYLOAD"])716 else: # Last fragmented packet717 fragmenting = 0718 frag_count +=1719 print "[R]-[FRAGMENTED DATA]-[DA:%s]-[SA:%s]-[MF:0]-[#seq:%i]-[#frag:%i]-[IFM:1]-[PAYLOAD = %s]" %(MAC.which_dir(x["mac_add2"]),MAC.which_dir(my_mac),x["N_SEQ"],x["N_FRAG"],x["PAYLOAD"])720 test_seq = x["N_FRAG"]+1 - frag_count721 if test_seq == 0:722 dato_leido = data_temp_reass + x["PAYLOAD"]723 State = "TRANSMITTING_ACK"724 WF_DATA_first_time = 1725 frag_count = 0 726 DATA_ok = 1727 fragmenting = 0728 if options.V: print "| WAITING_FOR_DATA | DATA_FRAG received (MF = 0)| TRANSMITTING_ACK |"729 MAC.send_ul_buff_packet(MAC_port, dato_leido)730 else: 731 State = "IDLE"732 WF_DATA_first_time = 1 733 DATA_ok = 0734 frag_count = 0735 fragmenting = 0736 if options.V: print "| WAITING_FOR_DATA | Error: one or more fragments not received | TRANSMITTING_ACK |"737 else: # More Fragments = 1. It's a fragment738 print "[R]-[FRAGMENTED DATA]-[DA:%s]-[SA:%s]-[MF:1]-[#seq:%i]-[#frag:%i]-[IFM:1]-[PAYLOAD = %s]" %(MAC.which_dir(x["mac_add2"]),MAC.which_dir(my_mac),x["N_SEQ"],x["N_FRAG"],x["PAYLOAD"])739 if options.V: print "| WAITING_FOR_DATA | DATA_FRAG received (MF = 1)| TRANSMITTING_ACK |"740 fragmenting = 1741 frag_count +=1742 DATA_ok = 1743 data_temp_reass = data_temp_reass + x["PAYLOAD"]744 State = "TX_ACK_FG" 745 else:746 DATA_ok = 0747 State = "WAITING_FOR_DATA" # Not a DATA packet748 WF_DATA_first_time = 0749 tdiff = (time.time() - t_1)750 assert (tslot - tdiff >=0),"Timing Error. Please increase the beta parameter."751 time.sleep(tslot - tdiff)752 T_DATA = T_DATA - (time.time() - t_1)753 if DATA_ok == 0:754 if T_DATA > 0:755 if options.V: print "| WAITING_FOR_DATA | DATA not received yet | WAITING_FOR_DATA |"756 State = "WAITING_FOR_DATA"757 else:758 # DATA didn't arrive, go to IDLE759 State = "IDLE"760 if options.V: print "| WAITING_FOR_DATA | DATA not received | IDLE |"761 DATA_ok = 1 762 763 #TX_ACK_FG STATE 764 elif State == "TX_ACK_FG":765 #print State766 values = {"duration":0, "mac_ra":dest_mac, "timestamp":time.time()} #dest_mac value copied from the previous Data packet767 print "[T]-[ACK]-[duration=%f]-[DA:%s]" %(values["duration"],MAC.which_dir(dest_mac))768 if options.V: print "| TX_ACK_FG | ACK sent | WAITING_FOR_DATA |"769 ACK = MAC.generate_pkt("ACK", options.interp, options.regime, values)770 packet_ACK = MAC.create_packet("PKT", ACK)771 MAC.transmit(packet_ACK, PHY_port)772 State = "WAITING_FOR_DATA"773 774 #TRANSMITTING_ACK STATE 775 elif State == "TRANSMITTING_ACK":776 #print State777 values = {"duration":0, "mac_ra":dest_mac, "timestamp":time.time()} #dest_mac value copied from the previous Data packet778 ACK = MAC.generate_pkt("ACK", options.interp, options.regime, values)779 packet_ACK = MAC.create_packet("PKT", ACK)780 print "[T]-[ACK]-[duration=%f]-[DA:%s]" %(values["duration"], MAC.which_dir(dest_mac))781 MAC.transmit(packet_ACK, PHY_port)782 State = "IDLE"783 if options.V: print "| TRANSMITTING_ACK | ACK sent | IDLE |"784785 786if __name__ == '__main__':787 try:788 main()789 except KeyboardInterrupt:
...
test_navigation.py
Source:test_navigation.py
...432 pass433 await asyncio.gather(frame.evaluate("() => window.stop()"), navigation_promise)434async def test_wait_for_nav_should_work_with_url_match(page, server):435 responses = [None, None, None]436 async def wait_for_nav(url: Any, index: int) -> None:437 async with page.expect_navigation(url=url) as response_info:438 pass439 responses[index] = await response_info.value440 response0_promise = asyncio.create_task(441 wait_for_nav(re.compile(r"one-style\.html"), 0)442 )443 response1_promise = asyncio.create_task(444 wait_for_nav(re.compile(r"\/frame.html"), 1)445 )446 response2_promise = asyncio.create_task(447 wait_for_nav(lambda url: "foo=bar" in url, 2)448 )449 assert responses == [None, None, None]450 await page.goto(server.EMPTY_PAGE)451 assert responses == [None, None, None]452 await page.goto(server.PREFIX + "/frame.html")453 assert responses[0] is None454 await response1_promise455 assert responses[1] is not None456 assert responses[2] is None457 await page.goto(server.PREFIX + "/one-style.html")458 await response0_promise459 assert responses[0] is not None460 assert responses[1] is not None461 assert responses[2] is None...
basic_80211mac.py
Source:basic_80211mac.py
1#!/usr/bin/env python2# Copyright 2005, 2006 Free Software Foundation, Inc.3 4# This file is part of GNU Radio5 6# GNU Radio is free software; you can redistribute it and/or modify7# it under the terms of the GNU General Public License as published by8# the Free Software Foundation; either version 3, or (at your option)9# any later version.10 11# GNU Radio is distributed in the hope that it will be useful,12# but WITHOUT ANY WARRANTY; without even the implied warranty of13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the14# GNU General Public License for more details.15 16# You should have received a copy of the GNU General Public License17# along with GNU Radio; see the file COPYING. If not, write to18# the Free Software Foundation, Inc., 51 Franklin Street,19# Boston, MA 02110-1301, USA.20# Projectname: uwicore@umh_80211_MAC21# Filename: uwicore_80211mac.py22# This script contains the MAC Finite State Machine (FSM) implementation developed by the Uwicore 23# Laboratory at the University Miguel Hernandez of Elche. More detailed information about the 24# FSM diagram transitions can be found at www.uwicore.umh.es/mhop-testbeds.html or at the publication:25# J.R. Gutierrez-Agullo, B. Coll-Perales and J. Gozalvez, "An IEEE 802.11 MAC Software Defined Radio Implementation for Experimental Wireless Communications and Networking Research", Proceedings of the 2010 IFIP/IEEE Wireless Days (WD'10), pp. 1-5, 20-22 October 2010, Venice (Italy).26# Ubiquitous Wireless Communications Research Laboratory 27# Uwicore, http://www.uwicore.umh.es28# Communications Engineering Department29# University Miguel Hernandez of Elche30# Avda de la Universidad, s/n31# 03202 Elche, Spain32# Release: April 201133# List of Authors:34# Juan R. Gutierrez-Agullo (jgutierrez@umh.es)35# Baldomero Coll-Perales (bcoll@umh.es)36# Dr. Javier Gozalvez (j.gozalvez@umh.es)37from optparse import OptionParser38from gnuradio.eng_option import eng_option39import uwicore_mac_utils as MAC40import time, sys, random41# Finite State Machine MAC main42def main():43 parser = OptionParser(option_class=eng_option, conflict_handler="resolve")44 parser.add_option("", "--PHYport", type="intx", default=8013,45 help="PHY communication socket port, [default=%default]")46 parser.add_option("", "--MACport", type="intx", default=8001,47 help="MAC communication socket port, [default=%default]")48 parser.add_option("-i", "--interp", type="intx", default=10,49 help="USRP2 interpolation factor value, [default=%default]\50 5 -> 802.11a/g, OFDM T_Symbol=4us, \51 10 -> 802.11p, OFDM T_Symbol=8us")52 parser.add_option("", "--regime", type="string", default="1",53 help="OFDM regimecode [default=%default]\54 1 -> 6 (3) Mbit/s (BPSK r=0.5), \55 2 -> 9 (4.5) Mbit/s (BPSK r=0.75), \56 3 -> 12 (6) Mbit/s (QPSK r=0.5), \57 4 -> 18 (9) Mbit/s (QPSK r=0.75), \58 5 -> 24 (12) Mbit/s (QAM16 r=0.5), \59 6 -> 36 (18) Mbit/s (QAM16 r=0.75), \60 7 -> 48 (24) Mbit/s (QAM64 r=0.66), \61 8 -> 54 (27) Mbit/s (QAM64 r=0.75)")62 parser.add_option("-n", "--node", type="intx", default=1,63 help="Number of USRP2 node, [default=%default]")64 parser.add_option("", "--beta", type="float", default=50000,65 help="Scaling Time Parameter, [default=%default]")66 parser.add_option("-t", "--time_slot", type="float", default=9e-6,67 help="Time slot value, [default=%default]")68 parser.add_option("-B", "--BI", type="float", default=1,69 help="Beacon Interval (BI) value in seconds, [default=%default]")70 parser.add_option("-S", "--SIFS", type="float", default=16e-6,71 help="Short Inter-frame space (SIFS) value, [default=%default]")72 parser.add_option('', "--retx", action="store_true", default=False,73 help="Retransmissions enabled, [default=%default]")74 parser.add_option('', "--RTS", action="store_true", default=True,75 help="RTS-threshold enabled, [default=%default]")76 parser.add_option('-v', "--V", action="store_true", default=False,77 help="Print debug information, [default=%default]")78 (options, args) = parser.parse_args ()79 80 my_mac = MAC.usrp2_node(options.node) # MAC address for this node81 dest_mac = MAC.usrp2_node(2) # Dummy value (updated when an incoming packet arrives)82 83 """84 IEEE 802.11-a MAC parameters85 """86 beta = options.beta # scaling time parameter87 tslot = options.time_slot * beta88 SIFS = options.SIFS * beta89 DIFS = SIFS + 2 * tslot90 Preamble = DIFS #16e-691 PLCP_header = 4e-6 * beta92 ACK_time = Preamble + PLCP_header93 CW_min = 1594 CW_max = 102395 RTS_THRESHOLD = 15096 dot11FragmentationTh = 103697 # TX time estimation for a CTS and an ACK packet98 empty_values = {"duration":0, "mac_ra":my_mac, "timestamp":time.time()} 99 CTS_empty = MAC.generate_pkt("CTS", options.interp, options.regime, empty_values)100 T_cts = CTS_empty["INFO"]["txtime"]101 ACK_empty = MAC.generate_pkt("ACK", options.interp, options.regime, empty_values)102 T_ack = ACK_empty["INFO"]["txtime"]103 104 # Set socket ports105 PHY_port = options.PHYport106 #PHYRX_port = options.PHYRXport107 MAC_port = options.MACport108 109 # Variables involving MAC tests110 testing = False # Testing mode active, used to conduct trials111 N_TESTS = 1000 # Number of tests112 N_TESTS_INI = N_TESTS 113 LONG_TESTS = 20 # Payload length for tests114 payload_test = "0000" + LONG_TESTS*'1' # Payload for tests115 test_with_sensing = True # Carrier Sensing (CS) allowed during the test116 total_processing_time = 0 # Total processing time117 t_sense_mean = 0 # CS average time118 t_csense = 0 # CS time119 t_MAC = 0 # MAC time120 t_MAC_mean = 0 # MAC average time121 packet_i=0 # Packets sent counter122 n_sensing = 0 # Number of CS performed123 124 # 'State' controls the state of the MAC125 State = "IDLE" 126 127 # Initial Conditions of the Finite State Machine128 NAV = 0 # Network Allocation Vector 129 N_RETRIES = 0 # Retries to send a packet counter130 busy_in_wfd = False # Busy in Wait_for_DIFS state131 BO_frozen = "NO" # Backoff frozen 132 TX_attempts = 0 # Tries to send a packet counter133 CTS_failed = False # CTS reception failed134 chan = "FREE" # Channel state = IDDLE135 N_SEQ = 0 # Sequence number counter136 N_FRAG = 0 # Fragment number counter137 first_tx = True # Is the first attempt to send a packet?138 frag_count = 0 # Counter used during fragmentation139 data_temp_reass = "" # Initial variable to perform de re-assembly process140 verbose = True # Shows when the MAC is in 'IDDLE' state141 beaconing = False # Is ON the Beaconing process?142 fragmenting = 0 # Is the packet received a fragment?143 144 if options.V:145 print "============================================="146 print " \t MAC layer: DCF + RTS/CTS"147 print "============================================="148 print "MAC address:",MAC.which_dir(my_mac)149 print "Rate = ",options.regime150 print "tslot(s): %f \t SIFS(s): %f"%(tslot,SIFS)151 print "DIFS(s): %f \t T_ACK(s): %f"%(DIFS, ACK_time)152 print "pseudo-random exp. BACKOFF [%i,%i]"%(CW_min, CW_max)153 if options.RTS: 154 print "RTS/CTS: enabled"155 print "\t with RTS Threshold(Bytes): %i \t" %RTS_THRESHOLD156 else: print "RTS/CTS: disabled"157 print "Fragmentation Threshold (Bytes):",dot11FragmentationTh158 if options.retx: print "Retransmissions: enabled"159 else: print "Retransmissions: disabled"160 print "Scaling time parameter = ",beta161 print "============================================="162 163 """164 Starts the MAC operation165 """166 while 1:167 #IDLE STATE168 if State == "IDLE":169 # Is there a DATA?170 reply_phy1, packet_phy1 = MAC.read_phy_response(PHY_port, "DATA")171 print State172 if reply_phy1 == "YES":173 verbose = True # Show when the MAC is IDLE174 x = packet_phy1["INFO"] # DATA packet addressed to this station175 '''176 #============================================================177 # /TEST/ UNCOMMENT TO CHECK RTS/CTS FUNCTIONALITY178 #============================================================179 # STEP 3/4: Node 1 --> DATA180 values = {"payload":"Paquete_que_llega12", "address1":x["mac_add1"], "address2":x["mac_add2"], "N_SEQ":N_SEQ, "N_FRAG":0, "timestamp":time.time()} 181 DATA_forced = MAC.generate_pkt("DATA", options.interp, options.regime, values)182 packet_DATA_forced = MAC.create_packet("PKT", DATA_forced)183 MAC.transmit(packet_DATA_forced, PHY_port)184 time.sleep(2*tslot)185 #============================================================186 '''187 dest_mac = x["mac_add2"]188 if x["MF"]==0: #More Fragments = 0189 if fragmenting == 0: # Not a fragmented packet190 print "[R]-[DATA]-[DA:%s]-[SA:%s]-[MF:0]-[IFM:1]-[PAYLOAD = %s]" %(MAC.which_dir(x["mac_add1"]),MAC.which_dir(x["mac_add2"]),x["PAYLOAD"])191 if options.V: print "| WAITING_FOR_DATA | DATA received | TRANSMITTING_ACK |"192 State = "TRANSMITTING_ACK"193 WF_DATA_first_time = 1 194 frag_count = 0195 MAC.send_ul_buff_packet(MAC_port, x["PAYLOAD"])196 else: # Last fragmented packet197 fragmenting = 0198 frag_count +=1199 print "[R]-[FRAGMENTED DATA]-[DA:%s]-[SA:%s]-[MF:0]-[#seq:%i]-[#frag:%i]-[IFM:1]-[PAYLOAD = %s]" %(MAC.which_dir(x["mac_add2"]),MAC.which_dir(my_mac),x["N_SEQ"],x["N_FRAG"],x["PAYLOAD"])200 test_seq = x["N_FRAG"]+1 - frag_count201 if test_seq == 0:202 dato_leido = data_temp_reass + x["PAYLOAD"]203 State = "TRANSMITTING_ACK"204 WF_DATA_first_time = 1205 frag_count = 0 206 fragmenting = 0207 if options.V: print "| WAITING_FOR_DATA | DATA_FRAG received (MF = 0)| TRANSMITTING_ACK |"208 MAC.send_ul_buff_packet(MAC_port, dato_leido)209 else: 210 WF_DATA_first_time = 1 211 frag_count = 0212 fragmenting = 0213 if options.V: print "| WAITING_FOR_DATA | Error: one or more fragments not received | IDLE |"214 else: # More Fragments = 1. It's a fragment215 print "[R]-[FRAGMENTED DATA]-[DA:%s]-[SA:%s]-[MF:1]-[#seq:%i]-[#frag:%i]-[IFM:1]-[PAYLOAD = %s]" %(MAC.which_dir(x["mac_add2"]),MAC.which_dir(my_mac),x["N_SEQ"],x["N_FRAG"],x["PAYLOAD"])216 if options.V: print "| WAITING_FOR_DATA | DATA_FRAG received (MF = 1)| TRANSMITTING_ACK |"217 fragmenting = 1218 frag_count +=1219 data_temp_reass = data_temp_reass + x["PAYLOAD"]220 State = "TX_ACK_FG" 221 222 223 # Check upper layer buffer for data to send224 else:225 reply_up, PAYLOAD = MAC.read_ul_buffer(MAC_port)226 if reply_up == "YES":227 verbose = True228 if options.V: print "| IDLE | MAC has DATA to Tx | WAIT_FOR_NAV |"229 State = "WAIT_FOR_NAV"230 elif reply_up == "BEACON":231 beaconing = True232 values = {"address2":my_mac, "N_SEQ":N_SEQ,"N_FRAG":0 ,"BI":options.BI, "timestamp":time.time()}233 print "[T]-[BEACON]-[SA:%s]-[BI=%f]-[#seq:%i]" %(MAC.which_dir(my_mac),options.BI,N_SEQ)234 if options.V: print "| IDLE | Send BEACON | IDLE |"235 BEACON = MAC.generate_pkt("BEACON", options.interp, options.regime, values)236 packet_BEACON = MAC.create_packet("PKT", BEACON)237 MAC.transmit(packet_BEACON, PHY_port)238 MAC.remove_ul_buff_packet(MAC_port)239 N_SEQ += 1240 beaconing = False241 if testing == True: # if True, it allows to switch manually to any state 242 t_testA = time.time() 243 packet_i +=1244 State = "WAIT_FOR_NAV" # Edit the state to switch to 245 246 if State == "IDLE": 247 time.sleep(tslot) # Time-slotted MAC248 249 250 #WAIT_FOR_NAV STATE251 elif State == "WAIT_FOR_NAV":252 print State253 NAV = MAC.update_NAV(time.time(), NAV, tslot)254 if NAV > 0:255 if options.V: print "| WAIT_FOR_NAV | NAV > 0 | WAIT_FOR_NAV |"256 State = "WAIT_FOR_NAV"257 else:258 if options.V: print "| WAIT_FOR_NAV | NAV = 0 | WAIT_FOR_DIFS |"259 State = "WAIT_FOR_DIFS"260 chan = "FREE"261 262 #WAIT_FOR_DIFS STATE263 elif State == "WAIT_FOR_DIFS":264 # This state performs the channel sensing process and decides whether the channel is BUSY or IDLE265 print State266 t_inicial=time.time()267 t_final=t_inicial + DIFS268 n_sensing=0269 while n_sensing < 2:270 #t_testB = time.time()271 channel_in_wfd, t = MAC.sense_channel(PHY_port)272 #t_testC = time.time()273 #assert (tslot - (t_testC-t_testB) >=0),"Timing Error. Please increase the beta parameter."274 #time.sleep(tslot-(t_testC-t_testB))275 assert (tslot - t >=0),"Timing Error. Please increase the beta parameter."276 time.sleep(tslot-t)277 if channel_in_wfd == "OCCUPIED":278 chan = "OCCUPIED"279 #t_csense = t_csense + (t_testC - t_testB)280 t_csense = t_csense + t281 n_sensing +=1 282 assert (t_final - time.time() >=0),"Timing Error. Please increase the beta parameter."283 time.sleep(t_final - time.time())284 t_csense = t_csense/3285 # print "Wait_for_DIFS operation time = ", (time.time()-t_inicial) # DEBUG286 287 if chan == "FREE":288 if BO_frozen == "NO" and busy_in_wfd == False and CTS_failed == False:289 BACKOFF = 0 # Channel IDLE for the first time, BOtimer = 0290 State = "BACKING_OFF"291 if options.V: print "| WAIT_FOR_DIFS | Channel idle | BACKING_OFF |" 292 else:293 if BO_frozen == "NO" and CTS_failed == False: # If it is the 1st time, set the CW294 BACKOFF = MAC.retry(TX_attempts, CW_min)295 TX_attempts = TX_attempts + 1296 #BO_frozen=="YES"297 BO_first_time = 1298 State = "IDLE"299 chan = "FREE"300 if options.V: print "| WAIT_FOR_DIFS | Channel busy | IDLE |"301 302 303 #BACKING_OFF STATE304 elif State == "BACKING_OFF":305 print State306 busy_in_wfd = False307 if BACKOFF == 0:308 BO_first_time = 1309 State = "TRANSMITTING_UNICAST"310 else:311 tx = time.time() 312 ch_status, t = MAC.sense_channel(PHY_port)313 314 if ch_status == "FREE": # Channel idle315 BACKOFF = BACKOFF - 1316 BO_first_time = 0 # Backoff process started, freeze CW value!317 if BACKOFF > 0: 318 if options.V: print "| BACKING_OFF | Channel idle (CW = %i) | BACKING_OFF |"%BACKOFF319 State = "BACKING_OFF"320 else:321 if options.V: print "| BACKING_OFF | Channel idle (CW = %i) | TRANSMITTING_UNICAST |"%BACKOFF 322 State = "TRANSMITTING_UNICAST"323 busy_in_wfd = False324 325 else: # Channel busy326 BACKOFF = BACKOFF - 1327 BO_first_time = 0 # Channel busy, CW frozen328 BO_frozen = "YES"329 State = "IDLE"330 if options.V:331 if options.V: print "| BACKING_OFF | Channel busy (CW = %i) | IDLE |"%BACKOFF 332 ty = time.time()333 assert (tslot - (ty - tx) >=0),"Timing Error. Please increase the beta parameter."334 time.sleep(tslot - (ty - tx))335 336 337 #TRANSMITTING_UNICAST STATE338 elif State == "TRANSMITTING_UNICAST":339 '''340 Send packet to PHY for its transmission using the USRP2341 packet = [MPDU][LENGHT][INFO] 342 pkt = [Header: PKT][Data: packet]343 '''344 print State345 fail_tx = False346 #if options.V: print "[%s]\t: TX DATA packet to PHY" % State347 if len(PAYLOAD) > dot11FragmentationTh:348 if options.V: print "| TRANSMITTING_UNICAST | Send Fragmented Data | TRANSMITTING_FRAGMENTED_PACKET |"349 State = "TRANSMITTING_FRAGMENTED_PACKET"350 first_time_fg = True351 WF_ACK_FG_first_time = True352 else:353 values = {"payload":PAYLOAD, "address1":dest_mac, "address2":my_mac, "N_SEQ":N_SEQ, "N_FRAG":N_FRAG, "timestamp":time.time()}354 print "[T]-[DATA]-[DA:%s]-[SA:%s]-[MF:0]-[#seq:%i]-[Payload = %s]" %(MAC.which_dir(dest_mac),MAC.which_dir(my_mac),N_SEQ,PAYLOAD)355 if options.V: print "| TRANSMITTING_UNICAST | Send DATA | WAITING_FOR_ACK |"356 N_SEQ += 1357 N_FRAG = 0358 if fail_tx == False:359 packet = MAC.generate_pkt("DATA", options.interp, options.regime, values)360 else:361 packet = MAC.generate_pkt("DATA_RETX", options.interp, options.regime, values)362 pkt = MAC.create_packet("PKT", packet)363 MAC.transmit(pkt, PHY_port)364 WF_ACK_first_time = 1 # First time in WAITING_FOR_ACK state 365 State = "WAITING_FOR_ACK"366 367 #WAITING_FOR_ACK STATE 368 elif State == "WAITING_FOR_ACK":369 print State370 if WF_ACK_first_time == 1:371 T_ACK = SIFS372 ta = time.time()373 any_packet, packet_phy = MAC.read_phy_response(PHY_port, "ACK")374 if any_packet == "YES":375 x = packet_phy["INFO"] 376 #print "[R]-[%s]-[DA:%s]-[duration:%f]-[IFM:1]" %(packet_phy["HEADER"],MAC.which_dir(x["RX_add"]),x["txtime"])377 print "[R]-[ACK]-[DA:%s]-[IFM:1]" %(MAC.which_dir(x["RX_add"]))378 '''379 #============================================================380 # /TEST/ UNCOMMENT TO CHECK RTS/CTS FUNCTIONALITY381 #============================================================382 # STEP 4/4: Node 2 --> ACK383 mac_ra = my_mac384 values = {"duration":x["txtime"], "mac_ra":mac_ra,"timestamp":time.time()} 385 ACK_forced = MAC.generate_pkt("ACK", options.interp, options.regime, values)386 packet_ACK_forced = MAC.create_packet("PKT", ACK_forced)387 MAC.transmit(packet_ACK_forced, PHY_port)388 time.sleep(tslot)389 #============================================================390 '''391 if options.V: print "| WAITING_FOR_ACK | ACK received | IDLE |"392 State = "IDLE"393 BACKOFF = 0394 WF_ACK_first_time = 1395 ACK_fin = 1 396 MAC.remove_ul_buff_packet(MAC_port) # Packet acknoweledged, remove from upper layers397 first_tx = True398 399 else:400 State = "WAITING_FOR_ACK" # Not an ACK401 WF_ACK_first_time = 0402 ACK_fin = 0403 404 ta_fin = time.time()405 assert (tslot - (ta_fin - ta) >=0),"Timing Error. Please increase the beta parameter."406 time.sleep(tslot - (ta_fin - ta))407 tb = time.time()408 T_ACK = T_ACK - (tb - ta)409 if ACK_fin == 0:410 if T_ACK > 0:411 if options.V: print "| WAITING_FOR_ACK | ACK not received yet | WAITING_FOR_ACK |"412 State = "WAITING_FOR_ACK"413 else:414 # Not ACK yet, Reset CW to CWmin and go to IDLE415 if options.retx == True:416 retx_retries = retx_retries - 1417 if retx_retries < 0:418 CW = CW_min 419 State = "IDLE"420 MAC.remove_ul_buff_packet(MAC_port) # drop the packet after maximum number of retries421 first_tx = True422 if options.V: print "| WAITING_FOR_ACK | Remove packet from upper layers | IDLE |"423 N_FRAG = 0 424 fail_tx = False425 else:426 if options.V: print "| WAITING_FOR_ACK | ACK not received (retries left = %i) | IDLE |"%retx_retries427 State = "IDLE"428 fail_tx = True429 else: 430 State = "IDLE"431 if options.V: print "| WAITING_FOR_ACK | Remove packet from upper layers | IDLE |"432 MAC.remove_ul_buff_packet(MAC_port) # No Re-TX!433 first_tx = True434 #TRANSMITTING_FRAGMENTED_PACKET STATE435 elif State == "TRANSMITTING_FRAGMENTED_PACKET":436 print State437 if first_time_fg == True:438 fragments = MAC.fragment(PAYLOAD, dot11FragmentationTh) #fragment the PAYLOAD based on a fragmentation threshold439 first_time_fg = False440 else:441 if len(fragments) > 1:442 payload_tmp = fragments[0]443 #Create packet with MORE FRAGMENT = 1 and payload = payload_tmp444 values = {"payload":payload_tmp, "address1":dest_mac, "address2":my_mac, "N_SEQ":N_SEQ, "N_FRAG":N_FRAG, "timestamp":time.time()}445 packet = MAC.generate_pkt("DATA_FRAG", options.interp, options.regime, values)446 N_SEQ += 1447 N_FRAG += 1448 pkt = MAC.create_packet("PKT", packet) 449 print "[T]-[FRAGMENTED DATA]-[DA:%s]-[SA:%s]-[MF:1]-[#seq:%i]-[#frag:%i]-[Payload = %s]" %(MAC.which_dir(dest_mac),MAC.which_dir(my_mac),N_SEQ,N_FRAG,payload_tmp)450 if options.V: print "| TRANSMITTING_FRAGMENTED_PACKET | Send DATA FRAG | WAIT_ACK_FRAGMENTED |"451 MAC.transmit(pkt, PHY_port)452 fragments.pop(0) #FIXME Retransmission for Fragmented packets is required453 fin_wait_ack_fragmented = False454 State = "WAIT_ACK_FRAGMENTED"455 elif len(fragments) == 1:456 payload_tmp = fragments[0]457 #Create packet with MORE FRAGMENT = 0 and payload = payload_tmp458 values = {"payload":payload_tmp, "address1":dest_mac, "address2":my_mac, "N_SEQ":N_SEQ, "N_FRAG":N_FRAG, "timestamp":time.time()}459 N_SEQ += 1460 N_FRAG += 1461 N_FRAG = 0462 print "[T]-[DATA]-[DA:%s]-[SA:%s]-[MF:0]-[#seq:%i]-[Payload = %s]" %(MAC.which_dir(dest_mac),MAC.which_dir(my_mac),N_SEQ, payload_tmp)463 if options.V: print "| TRANSMITTING_FRAGMENTED_PACKET | Send DATA FRAG (last fragment) | WAIT_ACK_FRAGMENTED |"464 packet = MAC.generate_pkt("DATA", options.interp, options.regime, values) 465 pkt = MAC.create_packet("PKT", packet) 466 MAC.transmit(pkt, PHY_port)467 fin_wait_ack_fragmented = True468 State = "WAIT_ACK_FRAGMENTED" 469 #WAIT_ACK_FRAGMENTED STATE 470 elif State == "WAIT_ACK_FRAGMENTED":471 print State472 if WF_ACK_FG_first_time == 1:473 T_ACK = SIFS474 ta1 = time.time()475 no_packet, packet_phy = MAC.read_phy_response(PHY_port, "ACK")476 if no_packet == "YES": # ACK addressed to this station477 x = packet_phy["INFO"]478 print "[R]-[ACK-FRAG]-[DA: %s]-[IFM:1]" %(MAC.which_dir(x["RX_add"]))479 if fin_wait_ack_fragmented == True: # Last fragment sent480 if options.V: print "| WAIT_ACK_FRAGMENTED | All fragments acknowledged | IDLE |"481 State = "IDLE"482 MAC.remove_ul_buff_packet(MAC_port) # Remove the packet from upper layers483 first_tx = True484 else:485 print "[R]-[ACK-FRAG]-[DA:%s]-[IFM:1]" %(MAC.which_dir(x["RX_add"]))486 if options.V: print "| WAIT_ACK_FRAGMENTED | ACK received | TRANSMITTING_FRAGMENTED_PACKET |"487 State = "TRANSMITTING_FRAGMENTED_PACKET"488 BACKOFF = 0489 WF_ACK_FG_first_time = 1490 ACK_FG_fin = 1 491 else:492 State = "WAIT_ACK_FRAGMENTED" # Not an ACK493 WF_ACK_FG_first_time = 0494 ACK_FG_fin = 0495 ta2=time.time()496 497 assert (tslot - (ta2 - ta1) >=0),"Timing Error. Please increase the beta parameter."498 time.sleep(tslot - (ta2 - ta1))499 tb = time.time()500 T_ACK = T_ACK - (tb - ta1)501 if ACK_FG_fin == 0:502 if T_ACK > 0:503 if options.V: print "| WAIT_ACK_FRAGMENTED | ACK not received yet | WAIT_ACK_FRAGMENTED |"504 State = "WAIT_ACK_FRAGMENTED"505 else: 506 if options.V: print "| WAIT_ACK_FRAGMENTED | ACK not received | IDLE |"507 State = "IDLE"508 MAC.remove_ul_buff_packet(MAC_port) # ACK not received within the Waiting_for_ack interval509 first_tx = True510 511 #TX_ACK_FG STATE 512 elif State == "TX_ACK_FG":513 print State514 values = {"duration":0, "mac_ra":dest_mac, "timestamp":time.time()} #dest_mac value copied from the previous Data packet515 print "[T]-[ACK]-[duration=%f]-[DA:%s]" %(values["duration"],MAC.which_dir(dest_mac))516 if options.V: print "| TX_ACK_FG | ACK sent | WAITING_FOR_DATA |"517 ACK = MAC.generate_pkt("ACK", options.interp, options.regime, values)518 packet_ACK = MAC.create_packet("PKT", ACK)519 MAC.transmit(packet_ACK, PHY_port)520 State = "WAITING_FOR_DATA"521 522 #TRANSMITTING_ACK STATE 523 elif State == "TRANSMITTING_ACK":524 print State525 #time.sleep(SIFS)526 values = {"duration":0, "mac_ra":dest_mac, "timestamp":time.time()} #dest_mac value copied from the previous Data packet527 ACK = MAC.generate_pkt("ACK", options.interp, options.regime, values)528 packet_ACK = MAC.create_packet("PKT", ACK)529 print "[T]-[ACK]-[duration=%f]-[DA:%s]" %(values["duration"], MAC.which_dir(dest_mac))530 MAC.transmit(packet_ACK, PHY_port)531 State = "IDLE"532 if options.V: print "| TRANSMITTING_ACK | ACK sent | IDLE |"533 534if __name__ == '__main__':535 try:536 main()537 except KeyboardInterrupt:...
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!