Beispiel #1
0
    def run(self):
        print("#### New thread for %s" % self.name)

        args = self._demo_ctrl.streaming_client_args
        print("args:", args)

        utils.config_logging(args)

        if args.socket_addr:
            client = SocketClient(args.socket_addr)
        else:
            port = args.serial_port or utils.autodetect_serial_port()
            client = UARTClient(port)

        try:
            client.connect()
        except Exception as e:
            print("Got exception:", e)

        session_info = client.setup_session(self.config)
        print("Session info:\n", session_info, "\n")

        client.start_session()
        while not self.terminating:
            sweep_info, sweep_data = client.get_next()

            d = self.process_data(sweep_data)
            if d is not None:
                self._demo_ctrl.put_cmd(str(d))
            if self.terminating:
                break
        client.disconnect()
def main():
    args = utils.ExampleArgumentParser().parse_args()
    utils.config_logging(args)

    if args.socket_addr:
        client = clients.SocketClient(args.socket_addr)
    elif args.spi:
        client = clients.SPIClient()
    else:
        port = args.serial_port or utils.autodetect_serial_port()
        client = clients.UARTClient(port)

    config = configs.EnvelopeServiceConfig()
    config.sensor = args.sensors

    print(config)

    connect_info = client.connect()
    print("connect info:")
    print_dict(connect_info)

    session_info = client.start_session(config)
    print("session_info:")
    print_dict(session_info)

    data_info, data = client.get_next()
    print("data_info:")
    print_dict(data_info)

    client.disconnect()
def main():
    args = utils.ExampleArgumentParser().parse_args()
    utils.config_logging(args)

    if args.socket_addr:
        client = SocketClient(args.socket_addr)
    elif args.spi:
        client = SPIClient()
    else:
        port = args.serial_port or utils.autodetect_serial_port()
        client = UARTClient(port)

    config = configs.IQServiceConfig()
    config.sensor = args.sensors
    config.range_interval = [0.2, 0.6]
    config.update_rate = 50

    info = client.start_session(config)

    interrupt_handler = utils.ExampleInterruptHandler()
    print("Press Ctrl-C to end session")

    fc = utils.FreqCounter(num_bits=(4 * 8 * info["data_length"]))

    while not interrupt_handler.got_signal:
        info, data = client.get_next()
        fc.tick()

    print("\nDisconnecting...")
    client.disconnect()
Beispiel #4
0
def main():
    args = utils.ExampleArgumentParser(num_sens=1).parse_args()
    utils.config_logging(args)

    if not check_connection(args):
        print(
            "Please check connection to radar sensor module or streaming server"
        )
        sys.exit(1)

    print("Please wait for the radar viewer to open your web browser...\n\n")

    threading.Thread(target=open_browser_delayed, args=()).start()
    http_server.start_server(args)
def main():
    args = utils.ExampleArgumentParser().parse_args()
    utils.config_logging(args)

    if args.socket_addr:
        client = SocketClient(args.socket_addr)
    elif args.spi:
        client = SPIClient()
    else:
        port = args.serial_port or utils.autodetect_serial_port()
        client = UARTClient(port)

    # Normally when using a single sensor, get_next will return
    # (info, data). When using mulitple sensors, get_next will return
    # lists of info and data for each sensor, i.e. ([info], [data]).
    # This is commonly called squeezing. To disable squeezing, making
    # get_next _always_ return lists, set:
    # client.squeeze = False

    config = configs.EnvelopeServiceConfig()
    config.sensor = args.sensors
    config.range_interval = [0.2, 0.3]
    config.update_rate = 5

    session_info = client.setup_session(config)
    print("Session info:\n", session_info, "\n")

    # Now would be the time to set up plotting, signal processing, etc.

    client.start_session()

    # Normally, hitting Ctrl-C will raise a KeyboardInterrupt which in
    # most cases immediately terminates the script. This often becomes
    # an issue when plotting and also doesn't allow us to disconnect
    # gracefully. Setting up an ExampleInterruptHandler will capture the
    # keyboard interrupt signal so that a KeyboardInterrupt isn't raised
    # and we can take care of the signal ourselves. In case you get
    # impatient, hitting Ctrl-C a couple of more times will raise a
    # KeyboardInterrupt which hopefully terminates the script.
    interrupt_handler = utils.ExampleInterruptHandler()
    print("Press Ctrl-C to end session\n")

    while not interrupt_handler.got_signal:
        info, data = client.get_next()
        print(info, "\n", data, "\n")

    print("Disconnecting...")
    client.disconnect()
def main():
    args = utils.ExampleArgumentParser().parse_args()
    utils.config_logging(args)

    if args.socket_addr:
        client = SocketClient(args.socket_addr)
    elif args.spi:
        client = SPIClient()
    else:
        port = args.serial_port or utils.autodetect_serial_port()
        client = UARTClient(port)

    client.squeeze = False

    config = configs.IQServiceConfig()
    config.sensor = args.sensors
    config.update_rate = 60

    session_info = client.setup_session(config)
    depths = utils.get_range_depths(config, session_info)

    fig_updater = ExampleFigureUpdater(depths)
    plot_process = PlotProcess(fig_updater)
    plot_process.start()

    client.start_session()

    interrupt_handler = utils.ExampleInterruptHandler()
    print("Press Ctrl-C to end session")

    while not interrupt_handler.got_signal:
        info, data = client.get_next()

        plot_data = {
            "amplitude": np.abs(data),
            "phase": np.angle(data),
        }

        try:
            plot_process.put_data(plot_data)
        except PlotProccessDiedException:
            break

    print("Disconnecting...")
    plot_process.close()
    client.disconnect()
def main():
    args = utils.ExampleArgumentParser().parse_args()
    utils.config_logging(args)

    if args.socket_addr:
        client = clients.SocketClient(args.socket_addr)
    elif args.spi:
        client = clients.SPIClient()
    else:
        port = args.serial_port or utils.autodetect_serial_port()
        client = clients.UARTClient(port)

    client.squeeze = False

    sensor_config = configs.SparseServiceConfig()
    sensor_config.sensor = args.sensors
    sensor_config.range_interval = [0.24, 1.20]
    sensor_config.sweeps_per_frame = 16
    sensor_config.hw_accelerated_average_samples = 60
    sensor_config.sampling_mode = sensor_config.SamplingMode.A
    sensor_config.profile = sensor_config.Profile.PROFILE_3
    sensor_config.gain = 0.6

    session_info = client.setup_session(sensor_config)

    pg_updater = PGUpdater(sensor_config, None, session_info)
    pg_process = PGProcess(pg_updater)
    pg_process.start()

    client.start_session()

    interrupt_handler = utils.ExampleInterruptHandler()
    print("Press Ctrl-C to end session")

    while not interrupt_handler.got_signal:
        data_info, data = client.get_next()

        try:
            pg_process.put_data(data)
        except PGProccessDiedException:
            break

    print("Disconnecting...")
    pg_process.close()
    client.disconnect()
def main():
    args = utils.ExampleArgumentParser().parse_args()
    utils.config_logging(args)

    if args.socket_addr:
        client = SocketClient(args.socket_addr)
    elif args.spi:
        client = SPIClient()
    else:
        port = args.serial_port or utils.autodetect_serial_port()
        client = UARTClient(port)

    client.squeeze = False

    sensor_config = get_sensor_config()
    sensor_config.sensor = args.sensors

    processing_config = get_processing_config()

    session_info = client.setup_session(sensor_config)

    pg_updater = PGUpdater(sensor_config, processing_config, session_info)
    pg_process = PGProcess(pg_updater)
    pg_process.start()

    client.start_session()

    interrupt_handler = utils.ExampleInterruptHandler()
    print("Press Ctrl-C to end session")

    processor = Processor(sensor_config, processing_config, session_info)

    while not interrupt_handler.got_signal:
        info, data = client.get_next()
        plot_data = processor.process(data)

        if plot_data is not None:
            try:
                pg_process.put_data(plot_data)
            except PGProccessDiedException:
                break

    print("Disconnecting...")
    pg_process.close()
    client.disconnect()
def main():
    args = utils.ExampleArgumentParser().parse_args()
    utils.config_logging(args)

    filename = "data.h5"
    if os.path.exists(filename):
        print("File '{}' already exists, won't overwrite".format(filename))
        sys.exit(1)

    if args.socket_addr:
        client = SocketClient(args.socket_addr)
    elif args.spi:
        client = SPIClient()
    else:
        port = args.serial_port or utils.autodetect_serial_port()
        client = UARTClient(port)

    config = configs.EnvelopeServiceConfig()
    config.sensor = args.sensors
    config.update_rate = 30

    session_info = client.setup_session(config)

    recorder = recording.Recorder(sensor_config=config,
                                  session_info=session_info)

    client.start_session()

    n = 100
    for i in range(n):
        data_info, data = client.get_next()
        recorder.sample(data_info, data)
        print("Sampled {:>4}/{}".format(i + 1, n), end="\r", flush=True)

    print()

    client.disconnect()

    record = recorder.close()
    os.makedirs(os.path.dirname(filename), exist_ok=True)
    recording.save(filename, record)
    print("Saved to '{}'".format(filename))
Beispiel #10
0
def main():
    args = utils.ExampleArgumentParser().parse_args()
    utils.config_logging(args)

    if args.socket_addr:
        client = clients.SocketClient(args.socket_addr)
    elif args.spi:
        client = clients.SPIClient()
    else:
        port = args.serial_port or utils.autodetect_serial_port()
        client = clients.UARTClient(port)

    client.squeeze = False

    sensor_config = configs.PowerBinServiceConfig()
    sensor_config.sensor = args.sensors
    sensor_config.range_interval = [0.1, 0.7]

    session_info = client.setup_session(sensor_config)

    pg_updater = PGUpdater(sensor_config, None, session_info)
    pg_process = PGProcess(pg_updater)
    pg_process.start()

    client.start_session()

    interrupt_handler = utils.ExampleInterruptHandler()
    print("Press Ctrl-C to end session")

    while not interrupt_handler.got_signal:
        data_info, data = client.get_next()

        try:
            pg_process.put_data(data)
        except PGProccessDiedException:
            break

    print("Disconnecting...")
    pg_process.close()
    client.disconnect()
def main():
    parser = utils.ExampleArgumentParser()
    parser.add_argument("-o", "--output-dir", type=str, required=True)
    parser.add_argument("--file-format", type=str, default="h5")
    parser.add_argument("--frames-per-file", type=int, default=10000)
    args = parser.parse_args()
    utils.config_logging(args)

    if os.path.exists(args.output_dir):
        print("Directory '{}' already exists, won't overwrite".format(args.output_dir))
        sys.exit(1)

    file_format = args.file_format.lower()
    if file_format == "np":
        file_format = "npz"

    if file_format not in ["h5", "npz"]:
        print("Unknown format '{}'".format(args.file_format))
        sys.exit(1)

    if args.frames_per_file < 10:
        print("Frames per file must be at least 10")
        sys.exit(1)

    if args.socket_addr:
        client = SocketClient(args.socket_addr)
    elif args.spi:
        client = SPIClient()
    else:
        port = args.serial_port or utils.autodetect_serial_port()
        client = UARTClient(port)

    config = configs.EnvelopeServiceConfig()
    config.sensor = args.sensors
    config.update_rate = 30

    session_info = client.start_session(config)

    os.makedirs(args.output_dir)

    interrupt_handler = utils.ExampleInterruptHandler()
    print("Press Ctrl-C to end session")

    total_num_frames = 0
    while not interrupt_handler.got_signal:
        record_count, num_frames_in_record = divmod(total_num_frames, args.frames_per_file)

        if num_frames_in_record == 0:
            recorder = recording.Recorder(sensor_config=config, session_info=session_info)

        data_info, data = client.get_next()
        recorder.sample(data_info, data)

        if num_frames_in_record + 1 == args.frames_per_file:
            record = recorder.close()
            filename = os.path.join(
                args.output_dir, "{:04}.{}".format(record_count + 1, file_format))
            print("Saved", filename)
            recording.save(filename, record)

        total_num_frames += 1
        print("Sampled {:>5}".format(total_num_frames), end="\r", flush=True)

    try:
        client.disconnect()
    except Exception:
        pass

    record_count, num_frames_in_record = divmod(total_num_frames, args.frames_per_file)
    if num_frames_in_record > 0:
        record = recorder.close()
        filename = os.path.join(
            args.output_dir, "{:04}.{}".format(record_count + 1, file_format))
        print("Saved", filename)
        recording.save(filename, record)
Beispiel #12
0
def main():
    args = utils.ExampleArgumentParser(num_sens=1).parse_args()
    utils.config_logging(args)

    if args.socket_addr:
        client = SocketClient(args.socket_addr)
    elif args.spi:
        client = SPIClient()
    else:
        port = args.serial_port or utils.autodetect_serial_port()
        client = UARTClient(port)

    config = configs.EnvelopeServiceConfig()
    config.sensor = args.sensors
    config.update_rate = 30

    session_info = client.setup_session(config)

    start = session_info["range_start_m"]
    length = session_info["range_length_m"]
    num_depths = session_info["data_length"]
    step_length = session_info["step_length_m"]
    depths = np.linspace(start, start + length, num_depths)
    num_hist = 2 * int(round(config.update_rate))
    hist_data = np.zeros([num_hist, depths.size])
    smooth_max = utils.SmoothMax(config.update_rate)

    app = QtWidgets.QApplication([])
    pg.setConfigOption("background", "w")
    pg.setConfigOption("foreground", "k")
    pg.setConfigOptions(antialias=True)
    win = pg.GraphicsLayoutWidget()
    win.setWindowTitle("Acconeer PyQtGraph example")

    env_plot = win.addPlot(title="Envelope")
    env_plot.showGrid(x=True, y=True)
    env_plot.setLabel("bottom", "Depth (m)")
    env_plot.setLabel("left", "Amplitude")
    env_curve = env_plot.plot(pen=pg.mkPen("k", width=2))

    win.nextRow()
    hist_plot = win.addPlot()
    hist_plot.setLabel("bottom", "Time (s)")
    hist_plot.setLabel("left", "Depth (m)")
    hist_image_item = pg.ImageItem()
    hist_image_item.translate(-2, start)
    hist_image_item.scale(2 / num_hist, step_length)
    hist_plot.addItem(hist_image_item)

    # Get a nice colormap from matplotlib
    hist_image_item.setLookupTable(utils.pg_mpl_cmap("viridis"))

    win.show()

    interrupt_handler = utils.ExampleInterruptHandler()
    win.closeEvent = lambda _: interrupt_handler.force_signal_interrupt()
    print("Press Ctrl-C to end session")

    client.start_session()

    while not interrupt_handler.got_signal:
        info, data = client.get_next()

        hist_data = np.roll(hist_data, -1, axis=0)
        hist_data[-1] = data

        env_curve.setData(depths, data)
        env_plot.setYRange(0, smooth_max.update(data))
        hist_image_item.updateImage(hist_data,
                                    levels=(0, np.max(hist_data) * 1.05))

        app.processEvents()

    print("Disconnecting...")
    app.closeAllWindows()
    client.disconnect()
Beispiel #13
0
def main():
    args = utils.ExampleArgumentParser().parse_args()
    utils.config_logging(args)

    if args.socket_addr:
        client = clients.SocketClient(args.socket_addr)
    elif args.spi:
        client = clients.SPIClient()
    else:
        port = args.serial_port or utils.autodetect_serial_port()
        client = clients.UARTClient(port)

    client.squeeze = False

    sensor_config = configs.EnvelopeServiceConfig()
    sensor_config.sensor = args.sensors
    sensor_config.range_interval = [0.2, 1.0]
    sensor_config.profile = sensor_config.Profile.PROFILE_2
    sensor_config.hw_accelerated_average_samples = 20
    sensor_config.downsampling_factor = 2

    session_info = client.setup_session(sensor_config)

    pg_updater = PGUpdater(sensor_config, None, session_info)
    pg_process = PGProcess(pg_updater)
    #pg_process.start()

    client.start_session()

    interrupt_handler = utils.ExampleInterruptHandler()
    print("Press Ctrl-C to end session")
    f = open("demo.txt", "w")
    while not interrupt_handler.got_signal:
        data_info, data = client.get_next()
        tempstr = " "
        #Array is within another Array, need to get address internal array
        dataArray = data[0]
        localMaxArray = [0, 0]
        breakVariable = 0
        iteratorJ = 0
        iteratorI = 0
        for x in dataArray:
            if (iteratorJ > 10):
                localMaxArray[0] = iteratorI - iteratorJ
                break
            else:
                if (x >= localMaxArray[0]):
                    localMaxArray[0] = x
                    iteratorJ = 0
                else:
                    iteratorJ = iteratorJ + 1
            iteratorI = iteratorI + 1
        while (dataArray[iteratorI] >= dataArray[iteratorI + 1]):
            iteratorI = iteratorI + 1
        iteratorJ = 0
        while (iteratorI < 827):
            if (iteratorJ > 10):
                localMaxArray[1] = iteratorI - iteratorJ
                break
            else:
                if (dataArray[iteratorI] >= localMaxArray[1]):
                    localMaxArray[1] = dataArray[iteratorI]
                    iteratorJ = 0
                else:
                    iteratorJ = iteratorJ + 1
            iteratorI = iteratorI + 1
        #try:
        #pg_process.put_data(data)
        #except PGProccessDiedException:
        #break
        print(
            math.floor(
                (((localMaxArray[1] - localMaxArray[0]) / 1.773) * 0.0393701) *
                10) / 10)
    print("Disconnecting...")
    f.close()
    #pg_process.close()
    client.disconnect()
Beispiel #14
0
def main():
    args = utils.ExampleArgumentParser(num_sens=1).parse_args()
    utils.config_logging(args)

    if args.socket_addr:
        client = SocketClient(args.socket_addr)
    elif args.spi:
        client = SPIClient()
    else:
        port = args.serial_port or utils.autodetect_serial_port()
        client = UARTClient(port)

    config = configs.IQServiceConfig()
    config.sensor = args.sensors
    config.update_rate = 10

    session_info = client.setup_session(config)
    depths = utils.get_range_depths(config, session_info)

    amplitude_y_max = 1000

    fig, (amplitude_ax, phase_ax) = plt.subplots(2)
    fig.set_size_inches(8, 6)
    fig.canvas.set_window_title("Acconeer matplotlib example")

    for ax in [amplitude_ax, phase_ax]:
        ax.set_xlabel("Depth (m)")
        ax.set_xlim(config.range_interval)
        ax.grid(True)

    amplitude_ax.set_ylabel("Amplitude")
    amplitude_ax.set_ylim(0, 1.1 * amplitude_y_max)
    phase_ax.set_ylabel("Phase")
    utils.mpl_setup_yaxis_for_phase(phase_ax)

    amplitude_line = amplitude_ax.plot(depths, np.zeros_like(depths))[0]
    phase_line = phase_ax.plot(depths, np.zeros_like(depths))[0]

    fig.tight_layout()
    plt.ion()
    plt.show()

    interrupt_handler = utils.ExampleInterruptHandler()
    print("Press Ctrl-C to end session")

    client.start_session()

    while not interrupt_handler.got_signal:
        info, data = client.get_next()

        amplitude = np.abs(data)
        phase = np.angle(data)

        max_amplitude = np.max(amplitude)
        if max_amplitude > amplitude_y_max:
            amplitude_y_max = max_amplitude
            amplitude_ax.set_ylim(0, 1.1 * max_amplitude)

        amplitude_line.set_ydata(amplitude)
        phase_line.set_ydata(phase)

        if not plt.fignum_exists(1):  # Simple way to check if plot is closed
            break

        fig.canvas.flush_events()

    print("Disconnecting...")
    plt.close()
    client.disconnect()
def main():
    parser = utils.ExampleArgumentParser()
    add_args(parser)
    args = parser.parse_args()

    if args.model_file_name:
        filename = args.model_file_name
    else:
        print("Not implemented!")
        sys.exit(1)

    keras_proc = kp.MachineLearning()
    model_data, message = keras_proc.load_model(filename)

    print(message.replace("<br>", "\n"))

    if not model_data["loaded"]:
        return False

    config = model_data["sensor_config"]
    feature_list = model_data["feature_list"]
    frame_settings = model_data["frame_settings"]

    print("\nFeature detection settings:")
    for setting in frame_settings:
        if "label" in setting:
            continue
        print("{}: {}".format(setting, frame_settings[setting]))

    feature_process = feature_proc.FeatureProcessing(config)
    feature_process.set_feature_list(feature_list)
    feature_process.set_frame_settings(frame_settings)

    utils.config_logging(args)

    if args.socket_addr:
        client = SocketClient(args.socket_addr)
    elif args.spi:
        client = SPIClient()
    else:
        port = args.serial_port or utils.autodetect_serial_port()
        client = UARTClient(port)

    session_info = client.setup_session(config)

    interrupt_handler = utils.ExampleInterruptHandler()
    print("\nPress Ctrl-C to end session")

    client.start_session()

    while not interrupt_handler.got_signal:
        info, sweep = client.get_next()

        data = {
            "sweep_data": sweep,
            "sensor_config": config,
            "session_info": session_info,
        }

        ml_frame_data = feature_process.feature_extraction(data)
        feature_map = ml_frame_data["current_frame"]["feature_map"]
        complete = ml_frame_data["current_frame"]["frame_complete"]

        if complete and feature_map is not None:
            predict = keras_proc.predict(feature_map)[0]
            label = predict["prediction"]
            confidence = predict["confidence"]
            print("Prediction: {:10s} ({:6.2f}%)\r".format(
                label, confidence * 100),
                  end="")

    print("Disconnecting...")
    client.disconnect()
def main():
    parser = utils.ExampleArgumentParser()
    parser.add_argument("-t", "--temp", type=str, required=True)
    parser.add_argument("-l", "--label", type=str,
                        required=False)  # Sätt till true sedan
    parser.add_argument("-o", "--output-file", type=str, required=True)
    parser.add_argument("-lim", "--limit-frames", type=int)
    #parser.add_argument("-a", "--angel", type=str, required=False)
    #parser.add_argument("-d", "--distance", type=str, required=True)
    args = parser.parse_args()
    utils.config_logging(args)

    try:
        float(args.temp)
    except:
        print("Temp value not a float. Make sure you use . instead of , !")
        sys.exit(1)

    valid_arguments = ["snow", "wet", "ice", "dry", "metal"]
    if args.label.lower() not in valid_arguments:
        print("Not a valid label. Only", *valid_arguments,
              sep=", "), print("are accepted labels!")
        sys.exit(1)

    if os.path.exists(args.output_file):
        print("File '{}' already exists, won't overwrite".format(
            args.output_file))
        sys.exit(1)

    _, ext = os.path.splitext(args.output_file)
    if ext.lower() not in [".h5", ".npz"]:
        print("Unknown format '{}'".format(ext))
        sys.exit(1)

    if args.limit_frames is not None and args.limit_frames < 1:
        print("Frame limit must be at least 1")
        sys.exit(1)

    if args.socket_addr:
        client = SocketClient(args.socket_addr)
    elif args.spi:
        client = SPIClient()
    else:
        port = args.serial_port or utils.autodetect_serial_port()
        client = UARTClient(port)

    config = configs.IQServiceConfig()
    config.sensor = args.sensors
    config.update_rate = 650  #Ändra samplingsfrekvens här
    config.range_interval = [0.06, 0.5]  #Avståndsintervall i meter
    config.profile = config.Profile.PROFILE_1
    config.repetition_mode = config.RepetitionMode.SENSOR_DRIVEN

    session_info = client.setup_session(config)

    recorder = recording.Recorder(sensor_config=config,
                                  session_info=session_info,
                                  temp=args.temp,
                                  label=args.label.lower())
    #angel=args.angel,
    #distance=args.distance
    client.start_session()

    interrupt_handler = utils.ExampleInterruptHandler()
    print("Press Ctrl-C to end session")

    i = 0
    while not interrupt_handler.got_signal:
        data_info, data = client.get_next()
        recorder.sample(data_info, data)

        i += 1

        if args.limit_frames:
            print("Sampled {:>4}/{}".format(i, args.limit_frames),
                  end="\r",
                  flush=True)

            if i >= args.limit_frames:
                break
        else:
            print("Sampled {:>4}".format(i), end="\r", flush=True)

    client.disconnect()

    record = recorder.close()
    recording.save(args.output_file, record)
    print("Saved to '{}'".format(args.output_file))
Beispiel #17
0
def main():
    # To simplify the examples, we use a generic argument parser. It
    # lets you choose between UART/SPI/socket, set which sensor(s) to
    # use, and the verbosity level of the logging.
    args = utils.ExampleArgumentParser().parse_args()

    # The client logs using the logging module with a logger named
    # acconeer.exptool.*. We call another helper function which sets up
    # the logging according to the verbosity level set in the arguments:
    # -q  or --quiet:   ERROR   (typically not used)
    # default:          WARNING
    # -v  or --verbose: INFO
    # -vv or --debug:   DEBUG
    utils.config_logging(args)

    # Pick client depending on whether socket, SPI, or UART is used
    if args.socket_addr:
        client = SocketClient(args.socket_addr)
    elif args.spi:
        client = SPIClient()
    else:
        port = args.serial_port or utils.autodetect_serial_port()
        client = UARTClient(port)

    # Create a configuration to run on the sensor. A good first choice
    # is the envelope service, so let's pick that one.
    config = configs.EnvelopeServiceConfig()

    # In all examples, we let you set the sensor(s) via the command line
    config.sensor = args.sensors

    # Set the measurement range [meter]
    config.range_interval = [0.2, 0.3]

    # Set the target measurement rate [Hz]
    config.update_rate = 10

    # Other configuration options might be available. Check out the
    # example for the corresponding service/detector to see more.

    client.connect()

    # In most cases, explicitly calling connect is not necessary as
    # setup_session below will call connect if not already connected.

    # Set up the session with the config we created. If all goes well,
    # some information/metadata for the configured session is returned.
    session_info = client.setup_session(config)
    print("Session info:\n", session_info, "\n")

    # Now would be the time to set up plotting, signal processing, etc.

    # Start the session. This call will block until the sensor has
    # confirmed that it has started.
    client.start_session()

    # Alternatively, start_session can be given the config instead. In
    # that case, the client will call setup_session(config) for you
    # before starting the session. For example:
    # session_info = client.start_session(config)
    # As this will call setup_session in the background, this will also
    # connect if not already connected.

    # In this simple example, we just want to get a couple of sweeps.
    # To get a sweep, call get_next. get_next will block until the sweep
    # is recieved. Some information/metadata is returned together with
    # the data.
    f = open("demo.txt","a");
    for i in range(3):
        data_info, data = client.get_next()
		
		
        print("Sweep {}:\n".format(i + 1), data_info, "\n", data, "\n")
        f.write(numpy.array2string(data) + "\n")
    f.close()
    # We're done, stop the session. All buffered/waiting data is thrown
    # away. This call will block until the server has confirmed that the
    # session has ended.
    client.stop_session()

    # Calling stop_session before disconnect is not necessary as
    # disconnect will call stop_session if a session is started.

    # Remember to always call disconnect to do so gracefully
    client.disconnect()
Beispiel #18
0
def main():
    args = utils.ExampleArgumentParser().parse_args()
    utils.config_logging(args)

    if args.socket_addr:
        client = SocketClient(args.socket_addr)
    elif args.spi:
        client = SPIClient()
    else:
        port = args.serial_port or utils.autodetect_serial_port()
        client = UARTClient(port)

    # Normally when using a single sensor, get_next will return
    # (info, data). When using mulitple sensors, get_next will return
    # lists of info and data for each sensor, i.e. ([info], [data]).
    # This is commonly called squeezing. To disable squeezing, making
    # get_next _always_ return lists, set:
    # client.squeeze = False

    config = configs.EnvelopeServiceConfig()
    config.sensor = args.sensors
    config.range_interval = [0.4, 0.7]
    config.update_rate = 20
    config.profile = config.Profile.PROFILE_2
    config.hw_accelerated_average_samples = 20
    config.downsampling_factor = 2
    session_info = client.setup_session(config)
    print("Session info:\n", session_info, "\n")

    # Now would be the time to set up plotting, signal processing, etc.

    client.start_session()

    # Normally, hitting Ctrl-C will raise a KeyboardInterrupt which in
    # most cases immediately terminates the script. This often becomes
    # an issue when plotting and also doesn't allow us to disconnect
    # gracefully. Setting up an ExampleInterruptHandler will capture the
    # keyboard interrupt signal so that a KeyboardInterrupt isn't raised
    # and we can take care of the signal ourselves. In case you get
    # impatient, hitting Ctrl-C a couple of more times will raise a
    # KeyboardInterrupt which hopefully terminates the script.
    interrupt_handler = utils.ExampleInterruptHandler()
    print("Press Ctrl-C to end session\n")

    is_performance_test_done = False

    while not interrupt_handler.got_signal:
        info, data = client.get_next()
        my_data = list(data)
        # Get the index of the highest measured signal strength from the list.
        index_max_signal_strength = my_data.index(max(my_data))
        # Calculate the distance of the highest measured signal strength in meters.
        if max(my_data) > 400:
            distance_of_strongest_signal_strength = 0.4 + (
                index_max_signal_strength * session_info["step_length_m"])
        else:
            distance_of_strongest_signal_strength = 1000
            print("No strong signal")
        #print(distance_of_strongest_signal_strength)
        #print("meters, signal strength : ")
        #print(index_max_signal_strength)
        #print("\r")
        print(max(my_data))
        # Run a performance test.
        if is_performance_test_done is False:
            is_performance_test_done = run_test(
                distance_of_strongest_signal_strength)
    print("Disconnecting...")
    client.disconnect()
def main():
    parser = utils.ExampleArgumentParser()
    parser.add_argument("-o", "--output-file", type=str, required=True)
    parser.add_argument("-l", "--limit-frames", type=int)
    args = parser.parse_args()
    utils.config_logging(args)

    if os.path.exists(args.output_file):
        print("File '{}' already exists, won't overwrite".format(
            args.output_file))
        sys.exit(1)

    _, ext = os.path.splitext(args.output_file)
    if ext.lower() not in [".h5", ".npz"]:
        print("Unknown format '{}'".format(ext))
        sys.exit(1)

    if args.limit_frames is not None and args.limit_frames < 1:
        print("Frame limit must be at least 1")
        sys.exit(1)

    if args.socket_addr:
        client = SocketClient(args.socket_addr)
    elif args.spi:
        client = SPIClient()
    else:
        port = args.serial_port or utils.autodetect_serial_port()
        client = UARTClient(port)

    config = configs.EnvelopeServiceConfig()
    config.sensor = args.sensors
    config.update_rate = 30

    session_info = client.setup_session(config)

    recorder = recording.Recorder(sensor_config=config,
                                  session_info=session_info)

    client.start_session()

    interrupt_handler = utils.ExampleInterruptHandler()
    print("Press Ctrl-C to end session")

    i = 0
    while not interrupt_handler.got_signal:
        data_info, data = client.get_next()
        recorder.sample(data_info, data)

        i += 1

        if args.limit_frames:
            print("Sampled {:>4}/{}".format(i, args.limit_frames),
                  end="\r",
                  flush=True)

            if i >= args.limit_frames:
                break
        else:
            print("Sampled {:>4}".format(i), end="\r", flush=True)

    print()

    client.disconnect()

    record = recorder.close()
    os.makedirs(os.path.dirname(os.path.abspath(args.output_file)),
                exist_ok=True)
    recording.save(args.output_file, record)
    print("Saved to '{}'".format(args.output_file))
Beispiel #20
0
def main():
    args = utils.ExampleArgumentParser().parse_args()
    utils.config_logging(args)

    if args.socket_addr:
        client = SocketClient(args.socket_addr)
    elif args.spi:
        client = SPIClient()
    else:
        port = args.serial_port or utils.autodetect_serial_port()
        client = UARTClient(port)

    # Normally when using a single sensor, get_next will return
    # (info, data). When using mulitple sensors, get_next will return
    # lists of info and data for each sensor, i.e. ([info], [data]).
    # This is commonly called squeezing. To disable squeezing, making
    # get_next _always_ return lists, set:
    # client.squeeze = False

    config = configs.EnvelopeServiceConfig()
    config.sensor = args.sensors
    config.range_interval = [0.2, 1]  # Range configuration
    config.update_rate = 50  # Data collection frequency

    session_info = client.setup_session(config)
    print("Session info:\n", session_info, "\n")

    # Now would be the time to set up plotting, signal processing, etc.

    client.start_session()

    # Normally, hitting Ctrl-C will raise a KeyboardInterrupt which in
    # most cases immediately terminates the script. This often becomes
    # an issue when plotting and also doesn't allow us to disconnect
    # gracefully. Setting up an ExampleInterruptHandler will capture the
    # keyboard interrupt signal so that a KeyboardInterrupt isn't raised
    # and we can take care of the signal ourselves. In case you get
    # impatient, hitting Ctrl-C a couple of more times will raise a
    # KeyboardInterrupt which hopefully terminates the script.
    interrupt_handler = utils.ExampleInterruptHandler()
    print("Press Ctrl-C to end session\n")

    # Here we make use of multiprocessing to run the data collection, sound wave computation, and
    # audio output separately. the intrerrupt_handler is passed in
    # so that the processes are stopped when a user hits Ctrl-C.

    with multiprocessing.Manager() as manager:

        shared_value = manager.Value(
            'd', 0)  # Shared variable to control the determined frequency.
        shared_amp = manager.Value(
            'd',
            0)  # Shared variable to control when a sound should be played.
        shared_wave = multiprocessing.Array('d', 4410)  # Shared Array

        p1 = multiprocessing.Process(target=data_handler,
                                     args=(client, interrupt_handler,
                                           shared_value, shared_amp))
        p2 = multiprocessing.Process(target=tune_gen,
                                     args=(interrupt_handler, shared_value,
                                           shared_amp, shared_wave))
        p3 = multiprocessing.Process(target=tune_play,
                                     args=(interrupt_handler, shared_wave))

        # Start processes
        p1.start()
        p2.start()
        p3.start()

        # Wait for processes to terminate before moving on
        p1.join()
        p2.join()
        p3.join()

    print("Disconnecting...")
    client.disconnect()
def main():
    args = utils.ExampleArgumentParser().parse_args()
    utils.config_logging(args)

    if args.socket_addr:
        client = clients.SocketClient(args.socket_addr)
    elif args.spi:
        client = clients.SPIClient()
    else:
        port = args.serial_port or utils.autodetect_serial_port()
        client = clients.UARTClient(port)

    client.squeeze = False

    range_start = 0.18
    range_end = 0.60
    num = int((range_end*100-range_start*100)/6)+1

    sensor_config = configs.SparseServiceConfig()
    sensor_config.sensor = args.sensors
    sensor_config.range_interval = [range_start, range_end]
    sensor_config.sweeps_per_frame = 16
    sensor_config.hw_accelerated_average_samples = 60
    sensor_config.sampling_mode = sensor_config.SamplingMode.A
    sensor_config.profile = sensor_config.Profile.PROFILE_2
    sensor_config.gain = 0.6

    session_info = client.setup_session(sensor_config)

    # pg_updater = PGUpdater(sensor_config, None, session_info)
    # pg_process = PGProcess(pg_updater)
    # pg_process.start()
    client.start_session()

    storage = []
    counter = 0
    sample = 300

    interrupt_handler = utils.ExampleInterruptHandler()
    print("Press Ctrl-C to end session")

    temp = np.zeros(num)
    
    #端末からデータを受け取り、フレームに入っているsweepの平均を取得し、tempに追加
    while not interrupt_handler.got_signal:
        data_info, data = client.get_next()
        counter += 1

        for sweep in data[0]:
            temp = temp + sweep

        temp = temp/len(data[0])
        storage.append(temp)
        temp = np.zeros(int(num))

        if(counter >= sample):
            break

    #300個のフレームから距離ごとに平均を取得
    # result = np.zeros(len(storage[0]))
    # for data in storage:
    #     result = result + data
    # result = result/len(storage)


    # clr=plt.rcParams['axes.prop_cycle'].by_key()['color']

    roop_count = 0
    prev_getData = np.loadtxt('sparse.csv')
    
    #生データ300個のフレームの平均を表示   
    show_raw_data = np.zeros(int(num))
    for frame in storage:
        show_raw_data += frame    
    show_curr_RawData = show_raw_data/sample
    
    ##保存していたデータの生データ300個のフレームの平均
    show_prev_RawData = []
    for data in prev_getData:
        show_prev_RawData.append(np.sum(data)/sample)

    x = np.arange(range_start*100,range_end*100+1,6)
    plt.subplot(1,3,1)
    plt.plot(x,show_curr_RawData,color='r')  
    plt.title("Raw Data(Current)") 
    plt.xlabel("Distance(cm)")
    plt.ylabel("Amptitude")
    plt.subplot(1,3,2)
    plt.plot(x,show_prev_RawData,color='b')  
    plt.title("Raw Data(Previous)") 
    plt.xlabel("Distance(cm)")
    plt.ylabel("Amptitude")
    plt.subplot(1,3,3)
    plt.title("Raw Data(Compare)") 
    plt.plot(x,show_curr_RawData,color='r')  
    plt.plot(x,show_prev_RawData,color='b')  
    plt.xlabel("Distance")
    plt.ylabel("Amptitude")
    
    # plt.tight_layout()
    # plt.show()
    # exit(1)
    

    #データを別々に表示
    for i in range(num):
        show_data = []
        plt.subplot(math.ceil(num/2),4,roop_count*2+1)
        plt.title(str(range_start*100+i*6)+"cm(Current)") 
        plt.xlabel("Quantity")
        plt.ylabel("Amptitude")
        for j in range(len(storage)):
            show_data.append(storage[j][i])
        plt.plot(range(1,sample+1),show_data,color='r')  

        plt.subplot(math.ceil(num/2),4,roop_count*2+2)
        plt.title(str(range_start*100+i*6)+"cm(Previous)") 
        plt.plot(range(1,sample+1),prev_getData[i],color='b')
        plt.xlabel("Quantity")
        plt.ylabel("Amptitude")
        roop_count += 1

    # plt.tight_layout()
    # plt.show()

    #データをあわせて表示
    for i in range(num):
        show_data = []
        plt.subplot(math.ceil(num/2),2,i+1)
        for j in range(len(storage)):
            show_data.append(storage[j][i])
        plt.plot(range(1,sample+1),show_data,color='r',label="Current Data")  
        plt.title(str(range_start*100+i*6)+"cm(Combination)") 
        plt.plot(range(1,sample+1),prev_getData[i],color='b',label="Previous Data")
        plt.xlabel("Quantity")
        plt.ylabel("Amptitude")
        plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0,fontsize='small')

    # plt.tight_layout()
    # plt.show()

    #ある距離の時系列データの遷移とそのデータのヒストグラムの表示   
    now_getData = []
    for i in range(num):
        show_data = []
        # plt.subplot(math.ceil(num/2),2,i+1)
        plt.subplot(math.ceil(num/2),4,i*2+1)
        plt.title(str(range_start*100+i*6)+"cm") 
        plt.xlabel("Distance") 
        plt.ylabel("Amptitude") 
        for j in range(len(storage)):
            show_data.append(storage[j][i])

        now_getData.append(show_data)
        # ヒストグラムの作成と表示
        # hist, bins = np.histogram(show_data,density=True)
        plt.plot(range(1,sample+1),show_data,color = "tomato")  
        plt.subplot(math.ceil(num/2),4,i*2+2)
        plt.hist(show_data,bins=10,density=True,color = "aqua")
        plt.title(str(range_start*100+i*6)+"cm") 
        plt.xlabel("Class") 
        plt.ylabel("Frequency") 
        # print("ヒストグラムの度数"+str(hist[0]))
        # print("階級を区切る値"+str(hist[1]))

    # plt.tight_layout()
    # plt.show()

    #ndarray型に変換し、保存
    # now_getData = np.array(now_getData)
    # np.savetxt('sparse.csv',now_getData)
    # exit(1)

    roop_count = 0
    prev_getData = np.loadtxt('sparse.csv')
    KL_storage = []
    JS_storage = []

    #ヒストグラムの度数からKLを算出
    for i in zip(prev_getData,now_getData):
        plt.subplot(math.ceil(num/2),4,roop_count*2+1)
        plt.title(str(range_start*100+roop_count*6)+"cm(Previous)") 
        plt.xlabel("Distance") 
        plt.ylabel("Frequency") 
        now_hist = plt.hist(i[0],bins=10,color = "lime")
        now_hist = normalization(np.array(now_hist[0]))

        # now_hist_normalization = normalization(np.array(now_hist[0]))
        # now_hist[0] = now_hist_normalization
        # print(now_hist)

        plt.subplot(math.ceil(num/2),4,roop_count*2+2)
        plt.title(str(range_start*100+roop_count*6)+"cm(Now)") 
        plt.xlabel("Distance") 
        plt.ylabel("Frequency") 
        prev_hist = plt.hist(i[1],bins=10,color = "deepskyblue")
        prev_hist = normalization(np.array(prev_hist[0]))
        # print("now_histの要素の数: "+str(len(now_hist[0])))
        # print("prev_histの要素の数: "+str(len(now_hist[0])))
        KL_value = KLdivergence(now_hist,prev_hist)
        print(str(range_start*100+roop_count*6)+"cm時のKL_Divergence: "+str(KL_value))
        JS_value = JSdivergence(now_hist,prev_hist)
        print(str(range_start*100+roop_count*6)+"cm時のJS_Divergence: "+str(JS_value)+"\n")
        KL_storage.append(KL_value)
        JS_storage.append(JS_value)
        roop_count += 1
    
    # plt.tight_layout()
    # plt.show()
    
    temp_KLlist = []
    temp_store_KLlist = []
    temp_JSlist = []
    temp_store_JSlist = []
    temp_KLlist.append(np.array(KL_storage))
    temp_JSlist.append(np.array(JS_storage))
    
    #ファイルからデータを読みこむ
    store_KLarr = np.loadtxt("KLDivergence_Sparse.csv",delimiter = ",")
    store_JSarr = np.loadtxt("JSDivergence_Sparse.csv",delimiter = ",")
    temp_store_KLlist.append(store_KLarr)
    temp_store_JSlist.append(store_JSarr)

    #データを追加
    store_KLarr = np.empty((0,num),int)
    store_JSarr = np.empty((0,num),int)
    for data in temp_store_KLlist:
        print(data)
        store_KLarr = np.append(store_KLarr,np.array(data),axis=0)
    # store_KLarr = np.append(store_KLarr,np.array(temp_store_KLlist),axis=0)
    for data in temp_store_KLlist:
        store_JSarr = np.append(store_JSarr,np.array(data),axis=0)
        # store_JSarr = np.append(store_JSarr,np.array(temp_store_JSlist),axis=0)
    store_KL = np.append(store_KLarr,np.array(temp_KLlist),axis=0)
    store_JS = np.append(store_JSarr,np.array(temp_JSlist),axis=0)

    #ファイルを保存
    store_KL = np.savetxt("KLDivergence_Sparse.csv",store_KL,delimiter=",")
    store_JS = np.savetxt("JSDivergence_Sparse.csv",store_JS,delimiter=",")

    #KL,JSの平均値
    # print("KL_Divergenceの平均値: "+str(np.sum(np.array(KL_storage))/num)+"\n")
    # print("JS_Divergenceの平均値: "+str(np.sum(np.array(JS_storage))/num)+"\n")
    
    #KLとJSを可視化
    X = list(range(int(range_start*100),int(range_end*100+1),6))
    plt.subplot(1,3,1)
    # plt.plot(range(len(KL_storage)),KL_storage,color='r',marker="o")  
    plt.plot(X,KL_storage,color='r',marker="o")  
    plt.title("KL Divergence") 
    plt.xlabel("Distance") 
    plt.ylabel("Amptitude") 

    plt.subplot(1,3,2)
    plt.plot(X,JS_storage,color='b',marker="o")  
    plt.title("JS Divergence") 
    plt.xlabel("Distance") 
    plt.ylabel("Amptitude") 

    plt.subplot(1,3,3)
    plt.plot(X,KL_storage,color='r',marker="o")  
    plt.plot(X,JS_storage,color='b',marker="o")  
    # plt.plot(X,KL_strage,color='r',marker="o",linewidth=0)  
    # plt.plot(X,JS_strage,color='b',marker="o",linewidth=0)  
    plt.title("Compare") 
    plt.xlabel("Distance") 
    plt.ylabel("Amptitude") 
    
    # plt.tight_layout()
    # plt.show()

    print("Disconnecting...")
    client.disconnect()