Beispiel #1
0
def make_packet(payload, samples_per_symbol, bits_per_symbol,
                access_code=default_access_code, pad_for_usrp=True,
                whitener_offset=0, whitening=True, coder=None):
    """
    Build a packet, given access code, payload, and whitener offset

    @param payload:               packet payload, len [0, 4096]
    @param samples_per_symbol:    samples per symbol (needed for padding calculation)
    @type  samples_per_symbol:    int
    @param bits_per_symbol:       (needed for padding calculation)
    @type bits_per_symbol:        int
    @param access_code:           string of ascii 0's and 1's
    @param whitener_offset        offset into whitener string to use [0-16)
    
    Packet will have access code at the beginning, followed by length, payload
    and finally CRC-32.
    """
    if not is_1_0_string(access_code):
        raise ValueError, "access_code must be a string containing only 0's and 1's (%r)" % (access_code,)

    if not whitener_offset >=0 and whitener_offset < 16:
        raise ValueError, "whitener_offset must be between 0 and 15, inclusive (%i)" % (whitener_offset,)

    (packed_access_code, padded) = conv_1_0_string_to_packed_binary_string(access_code)
    (packed_preamble, ignore) = conv_1_0_string_to_packed_binary_string(preamble)
    
    payload_with_crc = crc.gen_and_append_crc32(payload)
    if coder is not None:
      payload_with_crc = encode_rs(coder, payload_with_crc)

    #print "outbound crc =", string_to_hex_list(payload_with_crc[-4:])

    L = len(payload_with_crc)
    MAXLEN = len(random_mask_tuple)
    if L > MAXLEN:
        raise ValueError, "len(payload) must be in [0, %d]" % (MAXLEN,)

    if whitening:
        pkt = ''.join((packed_preamble, packed_access_code, make_header(L, whitener_offset),
                       whiten(payload_with_crc, whitener_offset), '\x55'))
    else:
        pkt = ''.join((packed_preamble, packed_access_code, make_header(L, whitener_offset),
                       (payload_with_crc), '\x55'))

    if pad_for_usrp:
        pkt = pkt + (_npadding_bytes(len(pkt), int(samples_per_symbol), bits_per_symbol) * '\x55')

    #print "make_packet: len(pkt) =", len(pkt)
    return pkt
Beispiel #2
0
def make_packet(payload, samples_per_symbol, bits_per_symbol,
                pad_for_usrp=True, whitener_offset=0, whitening=True, coder=None):
    """
    Build a packet, given access code, payload, and whitener offset

    @param payload:               packet payload, len [0, 4096]
    @param samples_per_symbol:    samples per symbol (needed for padding calculation)
    @type  samples_per_symbol:    int
    @param bits_per_symbol:       (needed for padding calculation)
    @type bits_per_symbol:        int
    @param whitener_offset        offset into whitener string to use [0-16)
    @param whitening:             Turn whitener on or off
    @type whitening:              bool
    
    Packet will have access code at the beginning, followed by length, payload
    and finally CRC-32.
    """

    if not whitener_offset >=0 and whitener_offset < 16:
        raise ValueError, "whitener_offset must be between 0 and 15, inclusive (%i)" % (whitener_offset,)

    payload_with_crc = crc.gen_and_append_crc32(payload)
    #print "outbound crc =", string_to_hex_list(payload_with_crc[-4:])
    if coder is not None:
      payload_with_crc = encode_rs(coder, payload_with_crc)

    L = len(payload_with_crc)
    MAXLEN = len(random_mask_tuple)
    if L > MAXLEN:
        raise ValueError, "len(payload) must be in [0, %d]" % (MAXLEN,)

    pkt_hd = make_header(L, whitener_offset)
    pkt_dt = ''.join((payload_with_crc, '\x55'))
    packet_length = len(pkt_hd) + len(pkt_dt)

    if pad_for_usrp:
        usrp_packing = _npadding_bytes(packet_length, samples_per_symbol, bits_per_symbol) * '\x55'
        pkt_dt = pkt_dt + usrp_packing

    if(whitening):
        pkt = pkt_hd + whiten(pkt_dt, whitener_offset)
    else:
        pkt = pkt_hd + pkt_dt

    #print "make_packet: len(pkt) =", len(pkt)

    return pkt
Beispiel #3
0
def make_packet(payload, samples_per_symbol, bits_per_symbol,
                preamble=default_preamble, access_code=default_access_code,
                pad_for_usrp=True, whitener_offset=0, whitening=True,
                calc_crc=True, repeat=1, interleave=None, debug=False):
    """
    Build a packet, given access code, payload, and whitener offset

    Args:
        payload: packet payload, len [0, 4096]
        samples_per_symbol: samples per symbol (needed for padding calculation) (int)
        bits_per_symbol: (needed for padding calculation) (int)
        preamble: string of ascii 0's and 1's
        access_code: string of ascii 0's and 1's
        pad_for_usrp: If true, packets are padded such that they end up a multiple of 128 samples(512 bytes)
        whitener_offset: offset into whitener string to use [0-16)
        whitening: Whether to turn on data whitening(scrambling) (boolean)
        calc_crc: Whether to calculate CRC32 or not (boolean)

    Packet will have access code at the beginning, followed by length, payload
    and finally CRC-32.
    """
    if not is_1_0_string(preamble):
        raise ValueError, "preamble must be a string containing only 0's and 1's (%r)" % (preamble,)

    if not is_1_0_string(access_code):
        raise ValueError, "access_code must be a string containing only 0's and 1's (%r)" % (access_code,)

    if not whitener_offset >=0 and whitener_offset < 16:
        raise ValueError, "whitener_offset must be between 0 and 15, inclusive (%i)" % (whitener_offset,)

    (packed_access_code, padded) = conv_1_0_string_to_packed_binary_string(access_code)
    (packed_preamble, ignore) = conv_1_0_string_to_packed_binary_string(preamble)

    if(calc_crc):
        payload_with_crc = crc.gen_and_append_crc32(payload)
    else:
        payload_with_crc = payload

    if repeat > 1:
        payload_with_crc = fec.repeat_encode(payload_with_crc, repeat)

        if interleave == 1:
            payload_with_crc = fec.interleave(payload_with_crc, repeat)
        elif interleave == 2:
            payload_with_crc = fec.shuffle_encode(payload_with_crc)

    L = len(payload_with_crc)

    if debug:
        print ""
        print "length =", L
        print "outbound crc =", string_to_hex_list(payload_with_crc[-4:])
        print "payload_with_crc =", string_to_hex_list(payload_with_crc)
        print ""


    MAXLEN = len(random_mask_tuple)
    if L > MAXLEN:
        raise ValueError, "len(payload) must be in [0, %d]" % (MAXLEN,)

    if whitening:
        pkt = ''.join((packed_preamble, packed_access_code, make_header(L, whitener_offset),
                       whiten(payload_with_crc, whitener_offset), '\x55'))
    else:
        pkt = ''.join((packed_preamble, packed_access_code, make_header(L, whitener_offset),
                       (payload_with_crc), '\x55'))

    if pad_for_usrp:
        pkt = pkt + (_npadding_bytes(len(pkt), int(samples_per_symbol), bits_per_symbol) * '\x55')

    #print "make_packet: len(pkt) =", len(pkt)
    return pkt
Beispiel #4
0
def make_packet(payload, samples_per_symbol, bits_per_symbol,
                options, access_code=default_access_code, pad_for_usrp=True,
                use_coding=False, #added on 09/20/12
				logging=-1,
                whitener_offset=0, whitening=True):
    """
    Build a packet, given access code, payload, and whitener offset

    @param payload:               packet payload, len [0, 4096]
    @param samples_per_symbol:    samples per symbol (needed for padding calculation)
    @type  samples_per_symbol:    int
    @param bits_per_symbol:       (needed for padding calculation)
    @type bits_per_symbol:        int
    @param access_code:           string of ascii 0's and 1's
    @param whitener_offset        offset into whitener string to use [0-16)
    
    Packet will have access code at the beginning, followed by length, payload
    and finally CRC-32.
    """
    if not is_1_0_string(access_code):
        raise ValueError, "access_code must be a string containing only 0's and 1's (%r)" % (access_code,)

    if not whitener_offset >=0 and whitener_offset < 16:
        raise ValueError, "whitener_offset must be between 0 and 15, inclusive (%i)" % (whitener_offset,)

    (packed_access_code, padded) = conv_1_0_string_to_packed_binary_string(access_code)
    (packed_preamble, ignore) = conv_1_0_string_to_packed_binary_string(preamble)
    
    #print "Length of payload is %d" % len(payload)
    
    payload_with_crc = crc.gen_and_append_crc32(payload)
    #print "outbound crc =", string_to_hex_list(payload_with_crc[-4:])
    
    #use_coding section copied from Thomas' ofdm_packet_util.py
    #added by Tri on 09/20/2012
    if use_coding:
        #print "use_coding is activated on tx"
        #Use coding and interleaving
        #Apply Reed-Solomon Code
        N = 8
        K = 4
        rs_encoder = Codec(N,K)
        payload_with_crc_and_rs = ''
        for n in range(0, len(payload_with_crc), K):
            payload_with_crc_and_rs = payload_with_crc_and_rs + rs_encoder.encode(payload_with_crc[n:n+K])

        #Interleave the RS symbols to put distance between the symbols under the same RS code
        payload_with_crc_and_rs_interleaved = ''
        for n in range(0, N, 1):
            payload_with_crc_and_rs_interleaved = payload_with_crc_and_rs_interleaved + payload_with_crc_and_rs[n:len(payload_with_crc_and_rs):N]
    else:
        # Skip coding and interleaving (although the variable name kind of indicates otherwise)
        payload_with_crc_and_rs_interleaved = payload_with_crc



    L = len(payload_with_crc_and_rs_interleaved)
    MAXLEN = len(random_mask_tuple)
    
    #print "coded payload length is %d" % L
    #print "MAXLEN is %d" % MAXLEN
    
    if L > MAXLEN:
        raise ValueError, "len(payload) must be in [0, %d]" % (MAXLEN,)

    if whitening:
        hd = make_header(L, whitener_offset)
        whitened_payload, success=whiten(payload_with_crc_and_rs_interleaved, whitener_offset)
        
        pkt = ''.join((packed_preamble, packed_access_code, make_header(L, whitener_offset),
                       whitened_payload, packed_preamble))
    else:
        pkt = ''.join((packed_preamble, packed_access_code, make_header(L, whitener_offset),
                       (payload_with_crc_and_rs_interleaved), packed_preamble))

    if pad_for_usrp:
        # print out number of padded bytes to make sure not to waste too much padded data
        #print "Preamble length is %d" % len(packed_preamble)
        #print "Access code length is %d" % len(packed_access_code)
        #print "Header length is %d" % len(hd)
        #print "Payload with crc length is %d" % len(payload_with_crc)
        #print "Payload with crc and RS length is %d" % len(payload_with_crc_and_rs_interleaved)
         
        #print "Packet length before padding is %d" % len(pkt)
        Nbytes_to_pad = _npadding_bytes(len(pkt), int(samples_per_symbol), bits_per_symbol)
        #print "Number of bytes padded to each packet is %d" % Nbytes_to_pad
        pkt = pkt + (Nbytes_to_pad * '\x55')
        
        print "Number of bytes padded to packet for USRP is %d" % Nbytes_to_pad
        print "Total packet length is %d bytes" % len(pkt)

    #print "make_packet: len(pkt) =", len(pkt)
    return pkt
def make_packet(payload, samples_per_symbol, bits_per_symbol,
                access_code=default_access_code, pad_for_usrp=True,
                whitener_offset=0, whitening=True):
    """
    Build a packet, given access code, payload, and whitener offset

    @param payload:               packet payload, len [0, 4096]
    @param samples_per_symbol:    samples per symbol (needed for padding calculation)
    @type  samples_per_symbol:    int
    @param bits_per_symbol:       (needed for padding calculation)
    @type bits_per_symbol:        int
    @param access_code:           string of ascii 0's and 1's
    @param whitener_offset        offset into whitener string to use [0-16)
    
    Packet will have access code at the beginning, followed by length, payload
    and finally CRC-32.
    """
    if not is_1_0_string(access_code):
        raise ValueError, "access_code must be a string containing only 0's and 1's (%r)" % (access_code,)

    if not whitener_offset >=0 and whitener_offset < 16:
        raise ValueError, "whitener_offset must be between 0 and 15, inclusive (%i)" % (whitener_offset,)

    (packed_access_code, padded) = conv_1_0_string_to_packed_binary_string(access_code)
    (packed_preamble, ignore) = conv_1_0_string_to_packed_binary_string(preamble)
    
    payload_with_crc = crc.gen_and_append_crc32(payload)
    #print "outbound crc =", string_to_hex_list(payload_with_crc[-4:])

    ########################
    # Error control code here
    nb = len(payload_with_crc)
    cl = Encoder.cat_codelength(nb)
    #print nb, cl
    codedpayload = payload_with_crc + payload_with_crc[0:cl-nb]
    Encoder.cat_encode(codedpayload,nb)

    ccnb = len(codedpayload);

    #print "Input to CC Enc has length ", ccnb 

    cccl = ccEncoder.cc3_codelength(ccnb,RSLEN)

    #cccodedpayload = codedpayload + codedpayload[0: cccl-ccnb]
    cccodedpayload = codedpayload + ('x' * (cccl-ccnb))
    ccEncoder.cc3_encode(cccodedpayload, ccnb, RSLEN)

    ######################

    # uncoded
    #L = len(payload_with_crc)
    
    # Xu: When coded with RS + CC
    L = len(cccodedpayload)

    MAXLEN = len(random_mask_tuple)

    # Commented by Xu, 2014-2-9
    #if L > MAXLEN:
    #    raise ValueError, "len(payload) must be in [0, %d]" % (MAXLEN,)

    # Xu: Never whitening
    '''
    if whitening:
        pkt = ''.join((packed_preamble, packed_access_code, make_header(L, whitener_offset),
                       whiten(payload_with_crc, whitener_offset), '\x55'))
    else:
        pkt = ''.join((packed_preamble, packed_access_code, make_header(L, whitener_offset),
                       (payload_with_crc), '\x55'))
    '''
    # coded
    pkt = ''.join((packed_preamble, packed_access_code, make_header(L, whitener_offset),
                       (cccodedpayload), '\x55'))

    if pad_for_usrp:
        pkt = pkt + (_npadding_bytes(len(pkt), int(samples_per_symbol), bits_per_symbol) * '\x55')

    #print "make_packet: len(pkt) =", len(pkt)
    return pkt
Beispiel #6
0
    def run(self):
        self.log_file.write('Time-' + time.strftime("%H%M%S") + '-Evnt-' +
                            'spectrum_watcher_thread_started\n')
        min_delay = 0.001  #min delay for CSMA implementation
        previous_spectrum_constraint_hz = []
        print 'master spectrum watch thread started'
        time.sleep(1)
        while self.keep_running:
            if self.state == 'ofdm':  #triggers sync mode if we're in ofdm mode...
                time.sleep(self.sensing_settings['period_sense']
                           )  #start timer for sensing
                self.log_file.write('Time-' + time.strftime("%H%M%S") +
                                    '-Evnt-' + 'sensing_triggered_watcher\n')

                for a in range(
                        3
                ):  #trigger slave to go to sync mode - this way slave mutes TX
                    self.ofdm_channel_available(min_delay)
                    if self.w_crc == 1:
                        frame = make_packet(
                            'sync mode', self.ofdm_settings['ofdm_packet_len'],
                            'B')
                        self.payload_src.send_pkt_s(frame)
                    else:
                        frame = crc.gen_and_append_crc32(
                            make_packet(
                                'sync mode',
                                self.ofdm_settings['ofdm_packet_len'] - 4,
                                'B'))
                        #crc32 adds 4 bytes
                        self.payload_src.send_pkt_s(frame)
                    #self.payload_src.send_pkt_s(make_packet('sync mode', self.ofdm_settings['ofdm_packet_len'], 'B'))
                    time.sleep(0.2)
                    print 'sending order to slave: switch to sync mode'

                self.idle_callback(
                )  #switch MASTER to idle mode - we can only conduct spectrum sensing if the slave is already out of OFDM mode

                if self.hardware_type == 'usrp':
                    spectrum_constraint_hz = spectrum_scan(
                        self.sensing_settings['ofdm_band_start'],
                        self.sensing_settings['ofdm_band_finish'],
                        self.sensing_settings['channel_rate'],
                        self.sensing_settings['srch_bw'],
                        self.sensing_settings['n_fft'], self.rf_source,
                        self.sense_rxpath, self.sensing_settings['method'],
                        self.sensing_settings['ed_threshold'],
                        self.sensing_settings['time_sense'] * 4,
                        False)  #True - plots results
                else:  #test purposes w/ TCP/UDP
                    spectrum_constraint_hz = []

                #spectrum_constraint_hz = [_rand_bad_freqs[randrange(5)]] #force some spectrum constraint...

                #if there is any change in spectrum analysis:
                if previous_spectrum_constraint_hz != spectrum_constraint_hz:
                    previous_spectrum_constraint_hz = spectrum_constraint_hz

                    self.generate_sync_data(
                        spectrum_constraint_hz
                    )  #generate sync data based on spectrum_constraint_hz
                    self.log_file.write(
                        'Time-' + time.strftime("%H%M%S") + '-Evnt-' +
                        'occupied_carriers-' +
                        str(len(self.sync_data['occupied_carriers'][0])))

                    #chage the state to post_ofdm_pre_sync and update sync data and ofdm data!
                    if self.update_sync_data_callback:
                        self.update_sync_data_callback(self.sync_data)

                #if there is NO change in spectrum analysis:
                else:
                    #chage the state to post_ofdm_pre_sync and update sync data and ofdm data!
                    if self.update_sync_data_callback:
                        self.update_sync_data_callback(self.sync_data)

            #if we are not in OFDM mode, there is no need to trigger anything
            else:
                time.sleep(.1)
Beispiel #7
0
    def slave_main_loop(self):
        self.log_file.write('Time-' + time.strftime("%H%M%S") + '-Evnt-' +
                            'main_loop_started\n')
        min_delay = 1e-6  # seconds
        forced_delay = 1e-6
        _ofdm_n_txd = 0

        self.pre_sync()

        #1st sync...
        print 'waiting for 1st sync'
        self.sync_nOK = True
        while self.sync_nOK:
            time.sleep(0.5)
        self.log_file.write('Time-' + time.strftime("%H%M%S") + '-Evnt-' +
                            '1st_sync_end(ok/Nok)\n')

        #rebuild sync data
        temp = ''
        for data in self.slave_raw_sync_data:
            temp += data
        slave_ack = True
        try:
            self.sync_data = ast.literal_eval(temp)
            #make sure MASTER received ack...
        except:  #catch any error that might occour
            slave_ack = False
            print 'error while recovering sync data'
            print 'going to sync again'
            self.log_file.write('Time-' + time.strftime("%H%M%S") + '-Evnt-' +
                                'bad_1st_sync_data\n')
            self.state = 'sync'  #jump to post_sync_pre_ofdm and then ofdm loop

        slave_ack = self.check_sync_words(
            slave_ack)  # check if sync words are correct

        if slave_ack:
            for i in range(3):
                self.sync_channel_available(min_delay)
                self.sync_txpath.send_pkt_s(
                    make_sync_packet('ACK',
                                     self.sync_settings['sync_packet_len'],
                                     'D', i))
                time.sleep(0.2)
                self.log_file.write('Time-' + time.strftime("%H%M%S") +
                                    '-Evnt-' + 'sent_ack_to_master\n')
            self.update_ofdm_settings()
            print 'end 1st sync, going to post_sync_pre_ofdm'
            self.log_file.write('Time-' + time.strftime("%H%M%S") + '-Evnt-' +
                                '1st_sync_ok\n')
            self.state = 'post_sync_pre_ofdm'

        self.start_slave_timeout_unlock_thread()
        self._slave_timeout_unlock.state = self.state

        while 1:  #slave loop
            if self.state == 'ofdm':
                payload = None
                signal.signal(
                    signal.SIGALRM,
                    self.signal_handler)  #initiate os.read execution monitor
                signal.alarm(2)  #set trigger time to 1s
                try:
                    payload = os.read(self.tun_fd, self.data_to_load)
                    if not payload:
                        self.payload_src.send_pkt_s(eof=True)
                        break
                except Exception:
                    print 'TIMEOUT'
                finally:
                    signal.alarm(0)  # disable alarm

                if payload != None:
                    print "Tx: len(payload) = %4d" % (len(payload), )
                    self.ofdm_channel_available(min_delay,
                                                forced_delay)  #CSMA - back off
                    if self.w_crc == 1:
                        frame = make_packet(
                            payload, self.ofdm_settings['ofdm_packet_len'],
                            'C')
                        self.payload_src.send_pkt_s(frame)
                    else:
                        frame = crc.gen_and_append_crc32(
                            make_packet(
                                payload,
                                self.ofdm_settings['ofdm_packet_len'] - 4,
                                'C'))
                        #crc32 adds 4 bytes
                        self.payload_src.send_pkt_s(frame)
                    _ofdm_n_txd += 1
                self._slave_timeout_unlock.state = self.state

            else:
                if self.state == 'sync':
                    print 'state:', self.state
                    self.log_file.write('Time-' + time.strftime("%H%M%S") +
                                        '-Evnt-' + 'state=sync\n')
                    self.sync_nOK = True
                    while self.sync_nOK:
                        time.sleep(0.5)

                    #rebuild sync data
                    temp = ''
                    for data in self.slave_raw_sync_data:
                        temp += data
                    slave_ack = True
                    try:  #try to recover sync data
                        self.sync_data = ast.literal_eval(temp)
                    except:  #catch any error that might occour
                        slave_ack = False
                        print 'error while recovering sync data'
                        print 'going to sync again'
                        self.log_file.write('Time-' + time.strftime("%H%M%S") +
                                            '-Evnt-' + 'bad_sync_data\n')
                        self.state = 'sync'  #jump to post_sync_pre_ofdm and then ofdm loop
                        self._slave_timeout_unlock.state = self.state

                    slave_ack = self.check_sync_words(
                        slave_ack)  # check if sync words are correct

                    if slave_ack:
                        #make sure MASTER received ack...
                        for i in range(3):
                            self.sync_channel_available(min_delay)
                            self.sync_txpath.send_pkt_s(
                                make_sync_packet('ACK', 512, 'D', i))
                            time.sleep(0.2)
                        self.log_file.write('Time-' + time.strftime("%H%M%S") +
                                            '-Evnt-' +
                                            'told_master_ack(sync)\n')
                        self.update_ofdm_settings()
                        print 'going to post_sync_pre_ofdm'
                        self.state = 'post_sync_pre_ofdm'  #jump to post_sync_pre_ofdm and then ofdm loop

                if self.state == 'post_sync_pre_ofdm':  #allways before ofdm
                    print 'state:', self.state
                    #sync off ofdm on
                    self.pre_ofdm()
                    print 'going to ofdm!'
                    self.state = 'ofdm'
                    self._slave_timeout_unlock.state = self.state

                if self.state == 'post_ofdm_pre_sync':  #only the watcher can call this one... turn off ofdm flowgraph
                    print 'state:', self.state
                    self.log_file.write('Time-' + time.strftime("%H%M%S") +
                                        '-Evnt-total_ofdm_txd_packets-' +
                                        str(_ofdm_n_txd) + '\n')
                    # ofdm off sync on
                    self.pre_sync()
                    print 'going to sync...'
                    self.state = 'sync'
                    self._slave_timeout_unlock.state = self.state

                if self.state == 'stop':
                    print 'state:', self.state
                    print self.sync_data
                    sys.exit(0)

                if self.state == 'idle':
                    print 'state', self.state
                    time.sleep(.001)
        '''
Beispiel #8
0
    def master_main_loop(self):
        self.log_file.write('Time-' + time.strftime("%H%M%S") + '-Evnt-' +
                            'main_loop_started\n')
        min_delay = 1e-6  # seconds
        forced_delay = 1e-6
        _ofdm_n_txd = 0

        #1ST Sensing
        if self.hardware_type == 'usrp':  #because it could be a 'net' source (tcp / udp)
            self.rf_source.set_samp_rate(self.ofdm_settings['ofdm_samp_rate'])
            self.rf_source.set_center_freq(
                uhd.tune_request(self.ofdm_settings['ofdm_fc'],
                                 self.ofdm_settings['ofdm_dc_offset']))
            self.rf_source.set_antenna(_sense_rx_ant, 0)

            #noise estimate
            offset = 0
            noise_band = 20000
            n_time = 1
            self.estimate_noise_level(
                noise_band, n_time,
                offset)  #----> receice FG must be / will be stopped!!!

            self.log_file.write('Time-' + time.strftime("%H%M%S") + '-Evnt-' +
                                'noise_estimate:' +
                                str(self.sensing_settings['ed_threshold']) +
                                '\n')
            print self.sensing_settings['ed_threshold']

            self.sense_rxpath = spectrum_probe(
                self.sensing_settings['time_sense'],
                self.ofdm_settings['ofdm_samp_rate'])
            self.tb.connect(self.rf_source, self.sense_rxpath)
            self.tb.start()  #start
            time.sleep(0.5)
        else:
            self.sense_rxpath = blocks.null_sink(gr.sizeof_gr_complex * 1)

        if self.hardware_type == 'usrp':
            #Compute the spectrum constraint based on the spectrum
            spectrum_constraint_hz = spectrum_scan(
                self.sensing_settings['ofdm_band_start'],
                self.sensing_settings['ofdm_band_finish'],
                self.sensing_settings['channel_rate'],
                self.sensing_settings['srch_bw'],
                self.sensing_settings['n_fft'], self.rf_source,
                self.sense_rxpath, self.sensing_settings['method'],
                self.sensing_settings['ed_threshold'],
                self.sensing_settings['time_sense'] * 4,
                True)  # 0.1 -> wait time before get samples, True = show plot
        else:
            spectrum_constraint_hz = []

        #self.safe_quit()
        #plots.show()
        #sys.exit(0)

        #spectrum_constraint_hz = [_rand_bad_freqs[randrange(5)]] #force some spectrum constraint...
        #spectrum_constraint_hz = []

        self.generate_sync_data(
            spectrum_constraint_hz
        )  #generate sync data based on spectrum_constraint_hz
        self.log_file.write('Time-' + time.strftime("%H%M%S") + '-Evnt-' +
                            'occupied_carriers-' +
                            str(len(self.sync_data['occupied_carriers'][0])) +
                            '\n')

        #end initial sense -> set tb flowgraph for sync
        self.pre_sync()

        #sync data --> occupied_carriers pilot_carriers pilot_symbols sync_word1 sync_word2 ofdm_fc ofdm_samp_rate ofdm_packet_len payload_mod
        #slice sync data in sync data packets
        temp = chunks_of_word(str(self.sync_data),
                              self.sync_settings['sync_packet_len'] - 10)
        sync_data_s = [''] * self.sink_len
        #fill sync packets w/ sync data --> the number of packets must be larger than the number of sync data slices...
        sync_data_s[:len(temp)] = temp
        print 'sd', len(str(self.sync_data))
        print 'sync data avail', self.sync_settings[
            'sync_packet_len'] * self.sink_len
        self.log_file.write('Time-' + time.strftime("%H%M%S") + '-Evnt-' +
                            'sync_data_len-' + str(len(str(self.sync_data))) +
                            '-sync_data_space_available-' +
                            str(self.sync_settings['sync_packet_len'] *
                                self.sink_len) + '\n')

        self.sync_nOK = True  #self.sync_nOK = False
        self.sync_slave(sync_data_s, min_delay)

        print 'going to post_sync_pre_ofdm'
        self.log_file.write('Time-' + time.strftime("%H%M%S") + '-Evnt-' +
                            '1st_sync_ok\n')
        self.state = 'post_sync_pre_ofdm'  #jump to post_sync_pre_ofdm and then ofdm loop
        #Start spectrum watch thread
        self.start_master_watch_thread(
        )  #update thread value: self._spectrum_watcher.value = new_value
        self._master_spectrum_watcher.state = self.state

        while 1:  # master loop
            if self.state == 'ofdm':
                payload = None
                signal.signal(
                    signal.SIGALRM,
                    self.signal_handler)  #initiate os.read execution monitor
                signal.alarm(2)  #set trigger time to 1s
                try:
                    payload = os.read(self.tun_fd, self.data_to_load)
                    if not payload:
                        self.payload_src.send_pkt_s(eof=True)
                        break
                except Exception:
                    print 'TIMEOUT'
                finally:
                    signal.alarm(0)  # disable alarm

                if payload != None:
                    print "Tx: len(payload) = %4d" % (len(payload), )
                    self.ofdm_channel_available(min_delay,
                                                forced_delay)  #CSMA - back off
                    if self.w_crc == 1:
                        frame = make_packet(
                            payload, self.ofdm_settings['ofdm_packet_len'],
                            'A')
                        self.payload_src.send_pkt_s(frame)
                    else:
                        frame = crc.gen_and_append_crc32(
                            make_packet(
                                payload,
                                self.ofdm_settings['ofdm_packet_len'] - 4,
                                'A'))
                        #crc32 adds 4 bytes
                        self.payload_src.send_pkt_s(frame)
                    _ofdm_n_txd += 1
                self._master_spectrum_watcher.state = self.state

            else:
                if self.state == 'sync':
                    print 'state:', self.state
                    temp = chunks_of_word(
                        str(self.sync_data),
                        self.sync_settings['sync_packet_len'] -
                        10)  #header adds 10 bytes
                    sync_data_s = [''] * self.sink_len
                    sync_data_s[:len(temp)] = temp
                    self.sync_slave(sync_data_s, min_delay)

                    print 'sync done'
                    print 'going to post_sync_pre_ofdm'
                    self.state = 'post_sync_pre_ofdm'
                    self._master_spectrum_watcher.state = self.state

                if self.state == 'post_sync_pre_ofdm':  #allways before ofdm
                    print 'state:', self.state
                    #sync off ofdm on
                    self.pre_ofdm()
                    #update master_watch_thread
                    self.update_master_spectrum_watcher()
                    print 'going to ofdm!'
                    self.state = 'ofdm'
                    self._master_spectrum_watcher.state = self.state

                if self.state == 'post_ofdm_pre_sync':  #only the watcher can call this one... turn off ofdm flowgraph
                    print 'state:', self.state
                    self.log_file.write('Time-' + time.strftime("%H%M%S") +
                                        '-Evnt-total_ofdm_txd_packets-' +
                                        str(_ofdm_n_txd) + '\n')
                    # ofdm off sync on
                    self.pre_sync()
                    print 'going to sync...'
                    self.state = 'sync'
                    self._master_spectrum_watcher.state = self.state

                if self.state == 'stop':
                    print 'state:', self.state
                    print 'exiting...'
                    sys.exit(0)

                if self.state == 'idle':
                    print 'state', self.state
                    time.sleep(.001)
        '''
Beispiel #9
0
def make_packet(
        payload,
        samples_per_symbol,
        bits_per_symbol,
        options,
        access_code=default_access_code,
        pad_for_usrp=True,
        use_coding=False,  #added on 09/20/12
        logging=-1,
        whitener_offset=0,
        whitening=True):
    """
    Build a packet, given access code, payload, and whitener offset

    @param payload:               packet payload, len [0, 4096]
    @param samples_per_symbol:    samples per symbol (needed for padding calculation)
    @type  samples_per_symbol:    int
    @param bits_per_symbol:       (needed for padding calculation)
    @type bits_per_symbol:        int
    @param access_code:           string of ascii 0's and 1's
    @param whitener_offset        offset into whitener string to use [0-16)
    
    Packet will have access code at the beginning, followed by length, payload
    and finally CRC-32.
    """
    if not is_1_0_string(access_code):
        raise ValueError, "access_code must be a string containing only 0's and 1's (%r)" % (
            access_code, )

    if not whitener_offset >= 0 and whitener_offset < 16:
        raise ValueError, "whitener_offset must be between 0 and 15, inclusive (%i)" % (
            whitener_offset, )

    (packed_access_code,
     padded) = conv_1_0_string_to_packed_binary_string(access_code)
    (packed_preamble,
     ignore) = conv_1_0_string_to_packed_binary_string(preamble)

    #print "Length of payload is %d" % len(payload)

    payload_with_crc = crc.gen_and_append_crc32(payload)
    #print "outbound crc =", string_to_hex_list(payload_with_crc[-4:])

    #use_coding section copied from Thomas' ofdm_packet_util.py
    #added by Tri on 09/20/2012
    if use_coding:
        #print "use_coding is activated on tx"
        #Use coding and interleaving
        #Apply Reed-Solomon Code
        N = 8
        K = 4
        rs_encoder = Codec(N, K)
        payload_with_crc_and_rs = ''
        for n in range(0, len(payload_with_crc), K):
            payload_with_crc_and_rs = payload_with_crc_and_rs + rs_encoder.encode(
                payload_with_crc[n:n + K])

        #Interleave the RS symbols to put distance between the symbols under the same RS code
        payload_with_crc_and_rs_interleaved = ''
        for n in range(0, N, 1):
            payload_with_crc_and_rs_interleaved = payload_with_crc_and_rs_interleaved + payload_with_crc_and_rs[
                n:len(payload_with_crc_and_rs):N]
    else:
        # Skip coding and interleaving (although the variable name kind of indicates otherwise)
        payload_with_crc_and_rs_interleaved = payload_with_crc

    L = len(payload_with_crc_and_rs_interleaved)
    MAXLEN = len(random_mask_tuple)

    #print "coded payload length is %d" % L
    #print "MAXLEN is %d" % MAXLEN

    if L > MAXLEN:
        raise ValueError, "len(payload) must be in [0, %d]" % (MAXLEN, )

    if whitening:
        hd = make_header(L, whitener_offset)
        whitened_payload, success = whiten(payload_with_crc_and_rs_interleaved,
                                           whitener_offset)

        pkt = ''.join(
            (packed_preamble, packed_access_code,
             make_header(L,
                         whitener_offset), whitened_payload, packed_preamble))
    else:
        pkt = ''.join((packed_preamble, packed_access_code,
                       make_header(L, whitener_offset),
                       (payload_with_crc_and_rs_interleaved), packed_preamble))

    if pad_for_usrp:
        # print out number of padded bytes to make sure not to waste too much padded data
        #print "Preamble length is %d" % len(packed_preamble)
        #print "Access code length is %d" % len(packed_access_code)
        #print "Header length is %d" % len(hd)
        #print "Payload with crc length is %d" % len(payload_with_crc)
        #print "Payload with crc and RS length is %d" % len(payload_with_crc_and_rs_interleaved)

        #print "Packet length before padding is %d" % len(pkt)
        Nbytes_to_pad = _npadding_bytes(len(pkt), int(samples_per_symbol),
                                        bits_per_symbol)
        #print "Number of bytes padded to each packet is %d" % Nbytes_to_pad
        pkt = pkt + (Nbytes_to_pad * '\x55')

        print "Number of bytes padded to packet for USRP is %d" % Nbytes_to_pad
        print "Total packet length is %d bytes" % len(pkt)

    #print "make_packet: len(pkt) =", len(pkt)
    return pkt