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.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()
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(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) sensor_config = get_sensor_config() sensor_config.sensor = args.sensors processing_config = None 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 = PhaseTrackingProcessor(sensor_config, processing_config, session_info) while not interrupt_handler.got_signal: info, sweep = client.get_next() plot_data = processor.process(sweep) 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))
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(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))
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()
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))
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()
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 = 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(): parser = argparse.ArgumentParser() parser.add_argument("-s", "--load-train-set", dest="server", help="IP of streaming server", default="127.0.0.1") args = parser.parse_args() filename = "model_data_speaker_sparse.npy" keras_proc = kp.MachineLearning() model_data, message = keras_proc.load_model(filename) print(message, "\n") if not model_data["loaded"]: print("Failed to load model!") sys.exit(1) try: client = SocketClient(args.server) except Exception: print("Failed to connect to server at {}!\n".format(args.server)) traceback.print_exc() sys.exit(1) conf_speaker = model_data["sensor_config"] conf_speaker.sensor = SENSOR_SPEAKER feature_list = model_data["feature_list"] feature_list[0]["sensors"] = [SENSOR_SPEAKER[0]] feature_list[1]["sensors"] = [SENSOR_SPEAKER[1]] frame_settings = model_data["frame_settings"] frame_settings["auto_threshold"] = 1.5 frame_settings["dead_time"] = 30 frame_settings["auto_offset"] = 15 frame_settings["collection_mode"] = "auto_feature_based" feature_process = feature_proc.FeatureProcessing(conf_speaker) feature_process.set_feature_list(feature_list) feature_process.set_frame_settings(frame_settings) handles = init_demo() handles["feature_process"] = feature_process handles["keras_proc"] = keras_proc # get session config for speaker mode info_speaker = client.setup_session(conf_speaker) handles["dist_processors"], handles[ "dist_tags"] = setup_distance_detectors(conf_speaker, info_speaker, SENSOR_SPEAKER) try: client.start_session() client.stop_session() except Exception: print("Failed to start session!") traceback.print_exc() sys.exit(1) demo_mode = "speaker" if USE_PRESENCE: # get session config for presence mode demo_mode = "presence" conf_presence = presence_detection.get_sensor_config() conf_presence.sensor = SENSOR_PRESENCE conf_presence.range_interval = PRESENCE_RANGE info_presence = client.setup_session(conf_presence) handles["presence_processor"] = setup_presence_detector( conf_presence, info_presence) if USE_PRESENCE: start_mode = "presence" else: start_mode = "speaker" print("Starting demo in {}-mode!".format(start_mode)) interrupt_handler = utils.ExampleInterruptHandler() print("Press Ctrl-C to end demo") client.start_session() while not interrupt_handler.got_signal: try: info, sweep = client.get_next() if demo_mode == "presence": new_mode = do_presence_mode(info, sweep, handles) else: data = { "sweep_data": sweep, "sensor_config": conf_speaker, "session_info": info_speaker, } new_mode = do_speaker_mode(info, data, handles) # switch between presence and speaker mode if new_mode != demo_mode: demo_mode = new_mode handles["led_handle"].double_flash("#000000") time.sleep(1) client.stop_session() if demo_mode == "presence": print("Switching to presence mode!\n") handles["led_handle"].double_flash("#000000") time.sleep(1) handles["idle_counts"] = 0 info_presence = client.setup_session(conf_presence) handles["presence_processor"] = setup_presence_detector( conf_presence, info_presence) if handles["play_mode"] == "play": color = "#00ff00" else: color = "#ff0000" handles["led_handle"].set_color(color, pos=[3, 4], brightness=0.1) else: print("Switching to speaker mode!\n") info_speaker = client.setup_session(conf_speaker) handles["led_handle"].set_color("#00ff00", pos=[3, 4], brightness=0.1) client.start_session() except Exception: traceback.print_exc() break print("Disconnecting...") if handles["play_mode"] == "play": handles["lms_handle"].queue.put("PAUSE") handles["lms_handle"].stop() handles["led_handle"].off() handles["led_handle"].exit() 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 = 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 = 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(): 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(): 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(): 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)