Hello. When I read data from the board, error D periodically passes. It
leads to bursts in the spectrum that fits in the figure. Please tell me how
you can remove this error or how it can be handled? I also attach the code
file.
[image: errorD.png]
"""
Curses FFT example using Python API
"""

import argparse
import static_value
import numpy as np
import uhd
import time
import zmq
import sys
import fcntl
import os
import ast
import threading as td
fd = sys.stdin.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
context = zmq.Context(1)




waveforms = {
    "sine": lambda n, tone_offset, rate: np.exp(n * 2j * np.pi * tone_offset / 
rate),
    "square": lambda n, tone_offset, rate: np.sign(waveforms["sine"](n, 
tone_offset, rate)),
    "const": lambda n, tone_offset, rate: 1 + 1j,
    "ramp": lambda n, tone_offset, rate:
    2 * (n * (tone_offset / rate) - np.floor(float(0.5 + n * (tone_offset / 
rate))))
}

data = np.array(
    list(map(lambda n: 10 * waveforms["const"](n, 1e6, 25e6),
             np.arange(
                 int(10 * np.floor(25e6 / 10e3)),
                 dtype=np.complex64))),
    dtype=np.complex64)


















def parse_args():
    """Parse the command line arguments"""
    parser = argparse.ArgumentParser()
    parser.add_argument("-a", "--args", default="addr=192.168.10.2", type=str)
    parser.add_argument("-f", "--freq", type=float, default=1500e6)
    parser.add_argument("-r", "--rate", default=static_value.rate, type=float)
    parser.add_argument("-g", "--gain", type=int, default=0)
    parser.add_argument("-c", "--channel", type=int, default=0)
    parser.add_argument("-n", "--nsamps", type=int, default=150000)
    parser.add_argument("--dyn", type=int, default=60)
    parser.add_argument("--ref", type=int, default=0)
    parser.add_argument("-s", "--sock", default="tcp://127.0.0.1:4001", 
type=str)
    return parser.parse_args()


def psd(nfft, samples):
    """Return the power spectral density of `samples`"""
    window = np.hanning(nfft)
    result = np.multiply(window, samples)
    result = np.fft.fftshift(np.fft.fft(result, nfft))
    result = np.square(np.abs(result))
    result = np.nan_to_num(10.0 * np.log10(result))
    result = np.abs(result)
    return result


def clip(minval, maxval, value):
    """Clip the value between a and b"""
    return min(minval, max(maxval, value))


def non_block_read(output):
    fd = output.fileno()
    fl = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
    try:
        return ast.literal_eval(output.read())
    except:
        return ""


def main():
    transmit_data_2 = np.array(np.fft.ifft(np.random.normal(1, 50.0, 400000)), 
dtype=np.float128)
    """Create Curses display of FFT"""
    args = parse_args()
    print(args.args)
    socket_transmit = context.socket(zmq.PUB)
    print(args.sock)
    socket_transmit.bind("{}".format(args.sock))

    socket_transmit.setsockopt(zmq.SNDHWM, 1)
    print ("OOOK")

    socket_reciev = context.socket(zmq.SUB)
    socket_reciev.bind("{}".format(args.sock + '1'))
    print(args.sock + '1')
    socket_reciev.setsockopt(zmq.SUBSCRIBE, '')
    print ("OOOK")

    usrp = uhd.usrp.MultiUSRP(args.args)

    # Set the USRP rate, freq, and gain
    usrp.set_rx_rate(args.rate, args.channel)
    usrp.set_rx_freq(uhd.types.TuneRequest(args.freq), args.channel)
    usrp.set_rx_gain(args.gain, args.channel)

    # Initialize the curses screen

    width = static_value.samples
    # Create a pad for the y-axis
    y_axis_width = 10
    # y_axis = cs.newwin(height, y_axis_width, 0, 0)

    # Create the buffer to recv samples
    num_samps = max(args.nsamps, width)
    samples = np.empty((1, num_samps), dtype=np.complex64)

    st_args = uhd.usrp.StreamArgs("fc32", "sc16")
    st_args.channels = [args.channel]

    streamer_tx = usrp.get_tx_stream(st_args)
    metadata_tx = uhd.types.TXMetadata()

    metadata = uhd.types.RXMetadata()
    streamer = usrp.get_rx_stream(st_args)
    buffer_samps = streamer.get_max_num_samps()
    recv_buffer = np.zeros((1, buffer_samps), dtype=np.complex64)
    recv_buffer1 = np.zeros((1, buffer_samps), dtype=np.complex64)

    stream_cmd = uhd.types.StreamCMD(uhd.types.StreamMode.start_cont)
    stream_cmd.stream_now = True
    streamer.issue_stream_cmd(stream_cmd)
    # db_step = float(args.dyn) / (height - 1.0)
    # db_start = db_step * int((args.ref - args.dyn) / db_step)
    # db_stop = db_step * int(args.ref / db_step)

    usrp.set_tx_bandwidth(25e6)
    list_freq = []
    list_tx_freq =[{910e6:10e6,950e6:10e6}]
    def rx_thread():
        try:
            while True:
                start = time.time()
                try:

                    message = socket_reciev.recv(flags=zmq.NOBLOCK)
                    if message[:8] == 'add_freq':

                        print(ast.literal_eval(message[8:]))
                        list_freq.append(ast.literal_eval(message[8:]))
                        # a message has been received
                    elif message[:8] == 'remove_f':
                        print('remove')
                        for i in range(len(list_freq)):
                            if list_freq[i].keys()[0] == message[8:]:
                                list_freq.pop(i)
                                break
                    elif message[:11] == 'change_gain':
                        usrp.set_rx_gain(float(message[11:]))
                        print(usrp.get_rx_gain())
                    elif message[:10] == 'add_txfreq':
                        list_tx_freq.append(ast.literal_eval(message[10:]))
                except zmq.Again as e:
                    # print "No message received yet"
                    pass

                if len(list_freq and list_tx_freq) == 0:
                    time.sleep(1)
                    continue
                for freq in list_freq:

                    buffer_end = np.empty((len(freq.values()[0]), width), 
dtype=np.complex64)
                    time1 = time.time()
                    for number, freqq in enumerate(freq[freq.keys()[0]]):

                        topic = freq.keys()[0]
                        # screen.clear()


                        # y_axis.clear()

                        # Create the vertical (dBfs) axis
                        # y_axis.addstr(0, 1, "{:> 6.2f} |-".format(db_stop))
                        # for i in range(1, height - 1):
                        #   label = db_stop - db_step * i
                        #   y_axis.addstr(i, 1, "{:> 6.2f} |-".format(label))
                        # try:
                        #    y_axis.addstr(height - 1, 1, "{:> 6.2f} 
|-".format(db_start))
                        # except cs.error:
                        #    pass
                        # y_axis.refresh()

                        # Receive the samples

                        usrp.set_rx_freq(uhd.types.TuneRequest(freqq), 
args.channel)
                        #while usrp.get_rx_sensor("lo_locked").to_bool() != 
True:
                         #   continue

                        # freq_list.append(usrp.get_rx_freq())
                        # recv_buffer = np.zeros((1, buffer_samps), 
dtype=np.complex64)
                        for s in np.arange(3):
                            recv_samps = 0
                            while recv_samps < num_samps:
                                samps = streamer.recv(recv_buffer, metadata)

                                if metadata.error_code != 
uhd.types.RXMetadataErrorCode.none:

                                    break
                                if samps:
                                    real_samps = min(num_samps - recv_samps, 
samps)
                                    samples[:, recv_samps:recv_samps + 
real_samps] = recv_buffer[:, 0:real_samps]
                                    recv_samps += real_samps

                        # stream_cmd = 
uhd.types.StreamCMD(uhd.types.StreamMode.stop_cont)
                        # streamer.issue_stream_cmd(stream_cmd)
                        # Get the power in each bin


                        buffer_end[number][:] = samples[args.channel][
                                                0:width]  # 
np.linspace(1*number,len(bins)*number,len(bins))

                        # 
socket.send(pickle.dumps(('set','key',time.time()-time1)))
                        # for i in range(y_axis_width, width):
                        #   vertical_slot = clip(height, 0, np.int(bins[i] / 
db_step))
                        #  try:
                        #     for j in range(vertical_slot, height):
                        #        screen.addch(j, i, '*')
                        # except cs.error:
                        #   pass
                        # screen.refresh()
                    # print('{}\n'.format(time.time()-time1))
                    socket_transmit.send("{}probel{}probel".format(topic, 
buffer_end.tostring()))


        except KeyboardInterrupt:
            pass
    def tx_thread():
        while True:
            for tx_freq_band in list_tx_freq:
                for r in range(len(tx_freq_band)):

                    
usrp.set_tx_freq(uhd.types.TuneRequest(tx_freq_band.keys()[r]), 0)
                    while usrp.get_tx_sensor("lo_locked").to_bool() != True:
                        continue

                    streamer_tx.send(transmit_data_2, metadata_tx)
                    time.sleep(1)
    thread=td.Thread(target=rx_thread)
    thread.start()
    #tx_tread= td.Thread(target=tx_thread)
    #tx_tread.start()
if __name__ == "__main__":
    main()
_______________________________________________
USRP-users mailing list
USRP-users@lists.ettus.com
http://lists.ettus.com/mailman/listinfo/usrp-users_lists.ettus.com

Reply via email to