Ejemplo n.º 1
0
def configure_x4(device_name,
                 record=False,
                 baseband=True,
                 x4_settings=x4_par_settings):
    mc = pymoduleconnector.ModuleConnector(device_name)
    # Assume an X4M300/X4M200 module and try to enter XEP mode
    app = mc.get_x4m200()
    # Stop running application and set module in manual mode.
    try:
        app.set_sensor_mode(XTS_SM_STOP, 0)  # Make sure no profile is running.
    except RuntimeError:
        # Profile not running, OK
        pass
    try:
        app.set_sensor_mode(XTS_SM_MANUAL, 0)  # Manual mode.
    except RuntimeError:
        pass
    xep = mc.get_xep()

    print('Clearing buffer')
    while xep.peek_message_data_float():
        xep.read_message_data_float()
    while xep.peek_message_data_string():
        xep.read_message_data_string()

    print('Start recorder if recording is enabled')
    if record:
        start_recorder(mc)

    print_x4_settings(xep)
    return xep
Ejemplo n.º 2
0
    def config_x4_sensor(self,
                         device_name,
                         min_range=-0.1,
                         max_range=0.4,
                         center_frequency=3,
                         FPS=10,
                         baseband=False):

        self.reset_buffer()

        self.mc = pymoduleconnector.ModuleConnector(device_name)

        app = self.mc.get_x4m300()
        # Stop running application and set module in manual mode.
        try:
            app.set_sensor_mode(XTID_SM_STOP,
                                0)  # Make sure no profile is running.
        except RuntimeError:
            # Profile not running, OK
            pass

        try:
            app.set_sensor_mode(XTID_SM_MANUAL, 0)  # Manual mode.
        except RuntimeError:
            # Maybe running XEP firmware only?
            pass

        try:
            self.xep = self.mc.get_xep()
            # set center frequency
            self.xep.x4driver_set_tx_center_frequency(center_frequency)

            # print(xep.x4driver_get_tx_center_frequency())

            self.xep.x4driver_set_dac_min(850)
            self.xep.x4driver_set_dac_max(1200)
            # Set integration
            self.xep.x4driver_set_iterations(64)
            self.xep.x4driver_set_pulses_per_step(25)
            # baseband?
            self.xep.x4driver_set_downconversion(int(baseband))
            # Start streaming of data
            self.xep.x4driver_set_frame_area(min_range, max_range)
            self.xep.x4driver_set_fps(FPS)

            self.connected = True
        except:
            print("error while config")
            return

        self.device_name = device_name
        self.FPS = FPS
        self.center_frequency = center_frequency
        self.min_range = min_range
        self.max_range = max_range
        # boolean
        self.baseband = baseband
Ejemplo n.º 3
0
def reset(device_name):
    """
    Resets the device profile and restarts the device

    Parameter:

        device_name: str
            Identifies the device being used for recording using it's port number.
    """
    mc = pymoduleconnector.ModuleConnector(device_name)
    xep = mc.get_xep()
    xep.module_reset()
    mc.close()
    sleep(3)
Ejemplo n.º 4
0
    def reset(self, device_name):
        try:
            mc = pymoduleconnector.ModuleConnector(device_name)
            xep = mc.get_xep()
            xep.module_reset()
            print("device find")
            mc.close()
            time.sleep(3)

            self.frame_history.clear()
            self.clutter = None

        except:
            print("Cannot find x4 device, please check connection or reconnect your device")
            raise
Ejemplo n.º 5
0
def playback_recording(meta_filename, baseband=False):
    """
    Plays back the recording.

    Parameters:

        meta_filename: str
            Name of meta file.
        baseband: boolean
            Check if recording with baseband iq data.
    """
    print("Starting playback for {}".format(meta_filename))
    player = pymoduleconnector.DataPlayer(meta_filename, -1)
    dur = player.get_duration()
    mc = pymoduleconnector.ModuleConnector(player)
    xep = mc.get_xep()
    player.set_playback_rate(1.0)
    player.set_loop_mode_enabled(True)
    player.play()

    print("Duration(ms): {}".format(dur))

    def read_frame():
        """Gets frame data from module"""
        d = xep.read_message_data_float()
        frame = np.array(d.data)
        if baseband:
            n = len(frame)
            frame = frame[:n // 2] + 1j * frame[n // 2:]
        return frame

    def animate(i):
        if baseband:
            line.set_ydata(abs(read_frame()))  # update the data
        else:
            line.set_ydata(read_frame())
        return line,

    fig = plt.figure()
    fig.suptitle("Plot playback")
    ax = fig.add_subplot(1, 1, 1)
    frame = read_frame()
    line, = ax.plot(frame)
    ax.set_ylim(0 if baseband else -0.03, 0.03)  # keep graph in frame (FIT TO YOUR DATA)
    ani = FuncAnimation(fig, animate, interval=10)
    plt.show()

    player.stop()
Ejemplo n.º 6
0
def configure_x4(device_name,
                 record=False,
                 baseband=False,
                 x4_settings=x4_par_settings):
    mc = pymoduleconnector.ModuleConnector(device_name)
    # Assume an X4M300/X4M200 module and try to enter XEP mode
    app = mc.get_x4m200()
    # Stop running application and set module in manual mode.
    try:
        app.set_sensor_mode(XTS_SM_STOP, 0)  # Make sure no profile is running.
    except RuntimeError:
        # Profile not running, OK
        pass
    try:
        app.set_sensor_mode(XTS_SM_MANUAL, 0)  # Manual mode.
    except RuntimeError:
        pass
    xep = mc.get_xep()

    print('Clearing buffer')
    while xep.peek_message_data_float():
        xep.read_message_data_float()
    print('Start recorder if recording is enabled')
    if record:
        start_recorder(mc)

    print('Set specific parameters')
    # Make sure that enable is set, X4 controller is programmed, ldos are enabled, and that the external oscillator has been enabled.
    xep.x4driver_init()
    x4_settings['downconversion'] = int(baseband)
    for variable, value in x4_settings.items():
        try:
            # if 'output_control' in variable:
            #     variable = 'output_control'
            setter = getattr(xep, 'x4driver_set_' + variable)
        except AttributeError as e:
            print("X4 does not have a setter function for '%s'." % variable)
            raise e

        if isinstance(value, tuple):
            setter(*value)
        else:
            setter(value)

        print("Setting %s to %s" % (variable, value))
    print_x4_settings(xep)
    return xep
Ejemplo n.º 7
0
    def __init__(self, device_name):

        self.reset(device_name)
        self.mc = pymoduleconnector.ModuleConnector(device_name)

        # Assume an X4M300/X4M200 module and try to enter XEP mode
        self.app = self.mc.get_x4m300()
        # Stop running application and set module in manual mode.
        try:
            self.app.set_sensor_mode(0x13,
                                     0)  # Make sure no profile is running.
        except RuntimeError:
            # Profile not running, OK
            pass

        try:
            self.app.set_sensor_mode(0x12, 0)  # Manual mode.
        except RuntimeError:
            # Maybe running XEP firmware only?
            pass
Ejemplo n.º 8
0
    def __init__(self, device_name, FPS, iterations, pulses_per_step, dac_min, dac_max, \
        area_start, area_end):
        self.device_name = device_name

        # radar parameters
        self.FPS = FPS
        self.iterations = iterations
        self.pulses_per_step = pulses_per_step
        self.dac_min = dac_min
        self.dac_max = dac_max
        self.area_start = area_start
        self.area_end = area_end
        self.bin_length = 8 * 1.5e8 / 23.328e9
        self.fast_sample_point = int((self.area_end - self.area_start) /
                                     self.bin_length + 2)
        #类型转换只取整

        self.reset()

        self.mc = pymoduleconnector.ModuleConnector(self.device_name)
        self.xep = self.mc.get_xep()

        self.sys_init()
def simple_xep_plot(device_name, record=False, baseband=False):
    FPS = 10
    directory = '.'
    reset(device_name)
    mc = pymoduleconnector.ModuleConnector(device_name)

    # Assume an X4M300/X4M200 module and try to enter XEP mode
    app = mc.get_x4m300()
    # Stop running application and set module in manual mode.
    try:
        app.set_sensor_mode(0x13, 0) # Make sure no profile is running.
    except RuntimeError:
        # Profile not running, OK
        pass

    try:
        app.set_sensor_mode(0x12, 0) # Manual mode.
    except RuntimeError:
        # Maybe running XEP firmware only?
        pass

    if record:
        recorder = mc.get_data_recorder()
        recorder.subscribe_to_file_available(pymoduleconnector.AllDataTypes, on_file_available )
        recorder.subscribe_to_meta_file_available(on_meta_file_available)

    xep = mc.get_xep()
    # Set DAC range
    xep.x4driver_set_dac_min(900)
    xep.x4driver_set_dac_max(1150)

    # Set integration
    xep.x4driver_set_iterations(16)
    xep.x4driver_set_pulses_per_step(26)

    xep.x4driver_set_downconversion(int(baseband))
    # Start streaming of data
    xep.x4driver_set_fps(FPS)

    def read_frame():
        """Gets frame data from module"""
        d = xep.read_message_data_float()
        frame = np.array(d.data)
         # Convert the resulting frame to a complex array if downconversion is enabled
        if baseband:
            n = len(frame)
            frame = frame[:n//2] + 1j*frame[n//2:]
        return frame

    def animate(i):
        if baseband:
            line.set_ydata(abs(read_frame())) # update the data
        else:
            line.set_ydata(read_frame())
        return line,

    fig = plt.figure()
    fig.suptitle("example version %d "%(__version__))
    ax = fig.add_subplot(1,1,1)
    ax.set_ylim(0 if baseband else -0.03,0.03) #keep graph in frame (FIT TO YOUR DATA)
    frame = read_frame()
    if baseband:
        frame = abs(frame)
    line, = ax.plot(frame)

    clear_buffer(mc)

    if record:
        recorder.start_recording(DataType.BasebandApDataType | DataType.FloatDataType, directory)

    ani = FuncAnimation(fig, animate, interval=FPS)
    try:
        plt.show()
    finally:
        # Stop streaming of data
        xep.x4driver_set_fps(0)
Ejemplo n.º 10
0
"""

from __future__ import print_function, division

import matplotlib.pyplot as plt
from matplotlib import mlab
import numpy as np

import pymoduleconnector
from pymoduleconnector.extras.auto import auto
from scipy import interpolate

device_name = auto()[0]
# print_module_info(device_name)
mc = pymoduleconnector.ModuleConnector(device_name)

# Assume an X4M300/X4M200 module and try to enter XEP mode
app = mc.get_x4m300()
# Stop running application and set module in manual mode.
try:
    app.set_sensor_mode(0x13, 0)  # Make sure no profile is running.
except RuntimeError:
    # Profile not running, OK
    pass

try:
    app.set_sensor_mode(0x12, 0)  # Manual mode.
except RuntimeError:
    # Maybe running XEP firmware only?
    pass
Ejemplo n.º 11
0
def recordData(devicePort, staticRemoval=False, startDist=0, endDist=5,
                                                                baseband=True):
    # Initialize module
    resetModule(devicePort)
    mc = pmc.ModuleConnector(devicePort)
    x4m03 = mc.get_xep()

    # Initialize FPS
    FPS = 20
    # DAC parameters
    x4m03.x4driver_set_dac_min(900)
    x4m03.x4driver_set_dac_max(1150)
    # Integration parameters
    x4m03.x4driver_set_iterations(16)
    x4m03.x4driver_set_pulses_per_step(26)
    # Baseband parameter method
    x4m03.x4driver_set_downconversion(int(baseband))

    # Edit radar range
    # Frame offset for X4M03 is fixed on 0.18 meters
    x4m03.x4driver_set_frame_area_offset(0.18)
    x4m03.x4driver_set_frame_area(startDist, endDist)

    # Start streaming of data
    x4m03.x4driver_set_fps(FPS)

    # Read frame method
    def readFrame():
        """Gets frame data from module"""
        d = x4m03.read_message_data_float()
        frame = np.array(d.data)
         # Convert the resulting frame to a complex array
         # if downconversion is enabled
        if baseband:
            n = len(frame)
            frame = frame[:n//2] + 1j*frame[n//2:]
        return frame

    # Prepare data for storing
    clearBuffer(mc)
    frame = readFrame()
    temp = np.arange(len(frame))
    dataAmp = np.array(temp);
    dataPhi = np.array(temp);

    startTime = datetime.now()
    # Prepare current time in string format for name of recording file
    nameTime = str(datetime.today().strftime('%Y-%m-%d_%H-%M'))

    # Loop for 15 seconds and record data
    while True:

        option = input('Insert filename to record or q to quit: ')
        if option.lower() == 'q':
            break
        else:
            frame = readFrame()
            frameAmp = np.abs(frame)
            for i in range(9):
                frameAmp[i] = 0.001
            framePhi = np.angle(frame)

            if staticRemoval:
                sum = 0
                for i in range(len(frameAmp)):
                    avg = sum / 180
                for i in range(len(frameAmp)):
                    frameAmp[i] -= avg

            dataAmp = np.vstack((dataAmp, frameAmp))
            dataPhi = np.vstack((dataPhi, framePhi))

            # Save data to the designated spot in csv format
            filenameAmp = storePath + 'Amp_' + option + '.csv'
            filenamePhi = storePath + 'Phi_' + option + '.csv'
            np.savetxt(filenameAmp, np.transpose(dataAmp), delimiter=", ")
            sleep(0.001)
            np.savetxt(filenamePhi, np.transpose(dataPhi), delimiter=", ")
            sleep(0.001)
            print('Recorded data')

    # Stop streaming of data
    x4m03.x4driver_set_fps(0)
Ejemplo n.º 12
0
def resetModule(devicePort):
    mc = pmc.ModuleConnector(devicePort)
    x4m03 = mc.get_xep()
    x4m03.module_reset()
    mc.close()
    sleep(3)
Ejemplo n.º 13
0
def checkConnection(devicePort):
    mc = pmc.ModuleConnector(devicePort)
    x4m03 = mc.get_xep()
    pong = x4m03.ping()
    print("Received pong, value is:",  hex(pong))
def plotModuleData(devicePort,
                   staticRemoval=False,
                   startDist=0,
                   endDist=5,
                   baseband=False):

    # Initialize module
    resetModule(devicePort)
    mc = pmc.ModuleConnector(devicePort)
    x4m03 = mc.get_xep()

    # Initialize FPS
    FPS = 20
    # DAC parameters
    x4m03.x4driver_set_dac_min(900)
    x4m03.x4driver_set_dac_max(1150)
    # Integration parameters
    x4m03.x4driver_set_iterations(16)
    x4m03.x4driver_set_pulses_per_step(26)
    # Baseband parameter method
    x4m03.x4driver_set_downconversion(int(baseband))

    # Edit radar range
    # Frame offset for X4M03 is fixed on 0.18 meters
    x4m03.x4driver_set_frame_area_offset(0.18)
    x4m03.x4driver_set_frame_area(startDist, endDist)

    # Start streaming of data
    x4m03.x4driver_set_fps(FPS)

    # Read frame method
    def readFrame():
        """Gets frame data from module"""
        d = x4m03.read_message_data_float()
        frame = np.array(d.data)
        # Convert the resulting frame to a complex array
        # if downconversion is enabled
        if baseband:
            n = len(frame)
            frame = frame[:n // 2] + 1j * frame[n // 2:]
        return frame

    def animate(i):
        frame = readFrame()
        frameAmp = np.abs(frame)
        # Loop for first 16 samples to virtually negate low isolation
        for i in range(16):
            frameAmp[i] = 1e-03
        framePhi = np.angle(frame)

        if staticRemoval:
            sum = 0
            for i in range(len(frameAmp)):
                sum += frameAmp[i]
            avg = sum / 180
            for i in range(len(frameAmp)):
                frameAmp[i] -= avg

        line1.set_ydata(frameAmp)
        line2.set_ydata(framePhi)

        return line1, line2

    # Create a figure with two subplots
    fig, (ax1, ax2) = plt.subplots(2, 1)
    # Configure subplots title, grid, ylims, subplot gap
    fig.suptitle('X4M03 Baseband Time Domain')
    ax1.set_ylim(-0.001, 0.03)
    ax1.title.set_text('Amplitude')
    ax1.set_xlabel('Bin #')
    ax1.set_ylabel('Norm. Amplitude [0->1]')
    ax2.set_ylim(-3.5, 3.5)
    ax2.title.set_text('Phase')
    ax2.set_xlabel('Bin #')
    ax2.set_ylabel('Phi[rad]')

    # Enable grid, set tick labels and adjust subplot spacing
    for ax in [ax1, ax2]:
        ax.grid()
    fig.subplots_adjust(hspace=.6)

    frame = readFrame()
    frameAmp = np.abs(frame)
    # Loop for first 16 samples to virtually negate low isolation
    for i in range(16):
        frameAmp[i] = 1e-03
    framePhi = np.angle(frame)

    if staticRemoval:
        sum = 0
        for i in range(len(frameAmp)):
            avg = sum / 180
        for i in range(len(frameAmp)):
            frameAmp[i] -= avg

    line1, = ax1.plot(frameAmp)
    line2, = ax2.plot(framePhi)

    clearBuffer(mc)

    ani = FuncAnimation(fig, animate, interval=FPS)
    try:
        plt.show()
    finally:
        print('Exiting...')
        # Stop streaming of data
        x4m03.x4driver_set_fps(0)
Ejemplo n.º 15
0
def simple_xep_plot(devicePort,
                    record=False,
                    baseband=True,
                    startDist=0,
                    endDist=5):

    FPS = 20
    directory = '.'
    resetModule(devicePort)
    mc = pymoduleconnector.ModuleConnector(devicePort)

    # Driver parameter initialization
    x4m03 = mc.get_xep()
    # Set DAC range
    x4m03.x4driver_set_dac_min(900)
    x4m03.x4driver_set_dac_max(1150)

    # Set integration
    x4m03.x4driver_set_iterations(16)
    x4m03.x4driver_set_pulses_per_step(26)

    x4m03.x4driver_set_downconversion(int(baseband))

    # Edit radar range
    # Frame offset for X4M03 is fixed on 0.18 meters
    x4m03.x4driver_set_frame_area_offset(0.18)
    x4m03.x4driver_set_frame_area(startDist, endDist)

    # Start streaming of data
    x4m03.x4driver_set_fps(FPS)

    def readFrame():
        """Gets frame data from module"""
        d = x4m03.read_message_data_float()
        frame = np.array(d.data)
        # Convert the resulting frame to a complex array if downconversion is
        # enabled
        if baseband:
            n = len(frame)
            frame = frame[:n // 2] + 1j * frame[n // 2:]
        return frame

    quit = False

    plt.ion()
    plt.figure()
    plt.title("X4M03 Baseband Data")

    clearBuffer(mc)
    frame = readFrame()

    t = np.arange(len(frame))

    data_amp = np.array(t)
    data_phi = np.array(t)

    while True:

        clearBuffer(mc)
        frame = readFrame()
        amps = np.abs(frame)
        phis = np.angle(frame)

        plt.subplot(211)
        plt.title("X4M03 Baseband Data")
        plt.subplots_adjust(hspace=0.4)

        plt.ylim((-0.001, 0.03))
        plt.plot(amps)
        plt.xlabel("Bin #")
        plt.ylabel("Normalized Amplitude")
        plt.pause(0.001)
        plt.grid(True)

        plt.subplot(212)
        plt.ylim((-3.5, 3.5))
        plt.plot(phis)
        plt.xlabel("Bin #")
        plt.ylabel("Phase [rad]")
        plt.pause(0.001)
        plt.grid(True)

        data_amp = np.vstack((data_amp, np.abs(frame)))
        data_phi = np.vstack((data_phi, np.angle(frame)))

        while True:
            print("Comands: q - quit, s - new record, Enter - new data, \
                   w name - save data to file")
            command = input("Enter command >> ")
            print("Command: ", command)

            if (command == "Q" or command == "q"):
                quit = True
                break
            elif (command == "s" or command == ""):
                plt.clf()
                data_amp = np.array(t)
                data_phi = np.array(t)
                break
            elif (command == "c"):
                break
            elif (command[0] == "w" and command[1] == " "):
                filename_amp = storePath + command[2:] + "_amp.csv"
                filename_phi = storePath + command[2:] + "_phi.csv"
                np.savetxt(filename_amp,
                           np.transpose(data_amp),
                           delimiter=", ")
                print("File recorded with name: ", filename_amp)
                np.savetxt(filename_phi,
                           np.transpose(data_phi),
                           delimiter=", ")
                print("File recorded with name: ", filename_phi)

        if (quit):
            break

    x4m03.x4driver_set_fps(0)
    print("Exiting...")
Ejemplo n.º 16
0
def get_config_info(mc):
    xep = mc.get_xep()
    # print("The DAC iteration is", xep.x4driver_get_iterations(), "\n")
    # print(xep.x4driver_get_dac_min())
    print("The FPS is %.1f \n" % xep.x4driver_get_fps())
    print("the Frame area is from %.1f to %.1f:" % (xep.x4driver_get_frame_area().start, \
        xep.x4driver_get_frame_area().end))
    # print("get decimation factor %d" % xep.get_decimation_factor())


if __name__ == "__main__":

    FPS = 10
    reset(my_device)
    mc = pymoduleconnector.ModuleConnector(my_device)

    xep = mc.get_xep()
    print(xep.get_system_info(2))

    # Set DAC range
    xep.x4driver_set_dac_min(900)
    xep.x4driver_set_dac_max(1150)

    # Set integration
    xep.x4driver_set_iterations(16)
    xep.x4driver_set_pulses_per_step(26)

    # Start streaming of data
    xep.x4driver_set_fps(FPS)
Ejemplo n.º 17
0
def reset(device_name):
    mc = pymoduleconnector.ModuleConnector(device_name)
    xep = mc.get_xep()
    xep.module_reset()
    mc.close()
    sleep(3)
Ejemplo n.º 18
0
parser.add_option(
    "-n",
    "--num-messages",
    dest="num_messages",
    type=int,
    default=0,
    help="how many matrices to read (0 = infinite)",
    metavar="INT")

(options, args) = parser.parse_args()

if not options.device_name:
    print("Please specify a device name, example: python %s -d COM4"%sys.argv[0])
    sys.exit(1)

mc = pymoduleconnector.ModuleConnector(options.device_name, 0)
time.sleep(1)

if options.interface == "x4m300":
    app = mc.get_x4m300()
    app.ping()
    app.load_profile(XTS_ID_APP_PRESENCE_2)
elif options.interface == "x4m200":
    app = mc.get_x4m200()
    app.ping()
    app.load_profile(XTS_ID_APP_RESPIRATION_2)
else:
    print("Interface not recognized.", file=sys.stderr)
    raise SystemExit(1)

# Flush all buffers