def get_cmdline_actuators(): """ This function also ensures triggers are shut off on exit. """ import sys from misc.utils import register_exit_signals if len(sys.argv) < 2: print("Please provide actuator numbers on the command line.") sys.exit(1) nums = [] for arg in sys.argv[1:]: num = get_num_from_maybe_name(arg) if num is None: print("Unrecognized actuator \"%s\"." % arg) sys.exit(1) nums.append(num) def sigh(sig, frame): set_triggers_by_number(on=[], off=nums) register_exit_signals(sigh) return nums
if not has_caught_sigint and signal == _signal.SIGINT: has_caught_sigint = True logger( 'Caught Ctrl-C. Mission paused. Ctrl-C again to quit, enter to resume.', copy_to_stdout=True) while True: ch = sys.stdin.readline() has_caught_sigint = False logger('Resuming mission!', copy_to_stdout=True) return else: cleanup() sys.exit(0) register_exit_signals(exit_handler) too_long_initial = True # if initially_killed: # logger('Sub is currently hard-killed. Waiting until unkilled.', copy_to_stdout=True) while True: begin_time = time.time() is_unkilled = not shm.switches.hard_kill.get() #is_soft_killed = shm.switches.soft_kill.get() #print(is_unkilled) # Note: Handled by the master mission #if initially_killed and is_unkilled and is_soft_killed: # # If un-hard killing for the first time, also un-soft kill to start mission # time.sleep(3)
def __call__(self, reload_on_enable=True, reload_on_change=True): m_logger = getattr(logger.module, self.module_name) m_logger("Running: " + str(self.module_name), True) # create the accessor for the capture source framework self.update_CMFs() quit = threading.Event() watcher = shm.watchers.watcher() watcher.watch(shm.vision_modules) def unblock(): quit.set() watcher.disable() [csf.unblock() for csf in self.capture_source_frameworks] # This is only to unblock update_CMFs for a second time... self.running = False camera_message_framework.running = False def cleanup(): main_thread.join(2) if main_thread.is_alive(): m_logger("Failed to kill module thread!", True) # How to kill the thread nicely here? self.module_framework.cleanup() m_logger("All cleaned up.", True) def sigh(sig, frame): unblock() cleanup() sys.exit(0) def reload_callback(): self.should_reload = True unblock() if reload_on_change: aph.detect_changes_to_self(reload_callback) if hasattr(shm.vision_modules, self.module_name): m_logger( "Module has shm variable! Now controlled by " "shm.vision_modules.%s" % self.module_name, True) module_shm = getattr(shm.vision_modules, self.module_name) else: module_shm = None def func(): has_been_disabled = False while not quit.is_set(): if module_shm is not None and not module_shm.get(): has_been_disabled = True watcher.wait(new_update=False) continue if has_been_disabled and reload_on_enable: self.should_reload = True break self.posted_images = [] # Grab images from all capture sources. next_images = [] acq_times = [] reset = False for f in self.capture_source_frameworks: res = f.get_next_frame() if res == camera_message_framework.FRAMEWORK_QUIT: return elif res == camera_message_framework.FRAMEWORK_DELETED: self.update_CMFs() reset = True break next_images.append(res[0]) acq_times.append(res[1]) if reset: continue # Feed images to the module. with self.option_lock: try: original_options = { option_name: self.options_dict[option_name].value for option_name in self.options_dict } curr_time = time.time() * 1000 avg_latency = sum( map(lambda t: curr_time - t, acq_times)) / len(acq_times) m_logger.log('{} image latency to {}: {}ms'.format( self.directions, self.module_name, avg_latency)) self.acq_time = acq_times self._next_images = self.preprocessor.process( *next_images) self.process(*self._next_images) except Exception as e: sys.stderr.write('{}\n'.format(e)) traceback.print_exc(file=sys.stderr) break if quit.is_set(): break # if the option value has changed, notify the watchers for option_name in original_options: option = self.options_dict[option_name] original_value = original_options[option_name] if original_value != option.value: self.module_framework.write_option( option.name, option.get_pack_values()) # Deal with any posted images. for (tag, image) in self.posted_images: if tag not in self.posted_images_set: self.module_framework.create_image( tag, self.max_buffer_size) img_ordering = { tag: i for (i, (tag, _)) in enumerate(self.posted_images) } self.module_framework.set_image_ordering( lambda x: img_ordering[x]) self.posted_images_set.add(tag) self.module_framework.write_image(tag, image, min(acq_times)) self.should_reload = False main_thread = threading.Thread(target=func) register_exit_signals(sigh) main_thread.start() main_thread.join() cleanup() if self.should_reload: aph.reload_self()
class ActuatorTest(object): actuators = ["torpedo_top", "torpedo_bottom", "left_marker", "right_marker"] @classmethod def run_test(cls): for act in cls.actuators: print("Firing %s..." % act) fire_actuators([act]) time.sleep(0.8) cls.cleanup() @classmethod def cleanup(cls): set_names_off(cls.actuators) if __name__ == "__main__": def interrupt(signal, frame): ActuatorTest.cleanup() sys.exit(0) register_exit_signals(interrupt) print("ATTENTION: This will fire both torpedos and markers!") print("\tBe sure that grabbers have not been reassigned") print("\tPress ENTER to continue or Control-C to quit") input() ActuatorTest.run_test()
has_caught_sigint = False def exit_handler(signal, frame): global has_caught_sigint if not has_caught_sigint and signal == _signal.SIGINT: has_caught_sigint = True logger('Caught Ctrl-C. Mission paused. Ctrl-C again to quit, enter to resume.', copy_to_stdout = True) while True: ch = sys.stdin.readline() has_caught_sigint = False logger('Resuming mission!', copy_to_stdout = True) return else: cleanup() sys.exit(0) register_exit_signals(exit_handler) too_long_initial = True while True: begin_time = time.time() try: task() except Exception as e: if not args.ignore_exceptions: cleanup() raise else: import traceback traceback.print_exc()
def __call__(self, reload_on_enable=True, reload_on_change=True): m_logger = getattr(logger.module, self.module_name) m_logger("Running: " + str(self.module_name), True) # create the accessor for the capture source framework self.update_CMFs() quit = threading.Event() watcher = shm.watchers.watcher() watcher.watch(shm.vision_modules) def unblock(): quit.set() watcher.disable() [csf.unblock() for csf in self.capture_source_frameworks] # This is only to unblock update_CMFs for a second time... self.running = False camera_message_framework.running = False def cleanup(): main_thread.join(2) if main_thread.is_alive(): m_logger("Failed to kill module thread!", True) # How to kill the thread nicely here? self.module_framework.cleanup() m_logger("All cleaned up.", True) def sigh(sig, frame): unblock() cleanup() sys.exit(0) def reload_callback(): self.should_reload = True unblock() if reload_on_change: aph.detect_changes_to_self(reload_callback) if hasattr(shm.vision_modules, self.module_name): m_logger("Module has shm variable! Now controlled by " "shm.vision_modules.%s" % self.module_name, True) module_shm = getattr(shm.vision_modules, self.module_name) else: module_shm = None def func(): has_been_disabled = False while not quit.is_set(): if module_shm is not None and not module_shm.get(): has_been_disabled = True watcher.wait(new_update=False) continue if has_been_disabled and reload_on_enable: self.should_reload = True break self.posted_images = [] # Grab images from all capture sources. next_images = [] acq_times = [] reset = False for f in self.capture_source_frameworks: res = f.get_next_frame() if res == camera_message_framework.FRAMEWORK_QUIT: return elif res == camera_message_framework.FRAMEWORK_DELETED: self.update_CMFs() reset = True break next_images.append(res[0]) acq_times.append(res[1]) if reset: continue # Feed images to the module. with self.option_lock: try: original_options = {option_name: self.options_dict[option_name].value for option_name in self.options_dict} curr_time = time.time()*1000 avg_latency = sum(map(lambda t: curr_time - t, acq_times)) / len(acq_times) m_logger.log('{} image latency to {}: {}ms'.format(self.directions, self.module_name, avg_latency)) self.acq_time = acq_times self.process(*next_images) except Exception as e: sys.stderr.write('{}\n'.format(e)) traceback.print_exc(file=sys.stderr) if quit.is_set(): break # if the option value has changed, notify the watchers for option_name in original_options: option = self.options_dict[option_name] original_value = original_options[option_name] if original_value != option.value: self.module_framework.write_option(option.name, option.get_pack_values()) # Deal with any posted images. for (tag, image) in self.posted_images: if tag not in self.posted_images_set: self.module_framework.create_image(tag, max(self.buffer_size)) img_ordering = {tag: i for (i, (tag, _)) in enumerate(self.posted_images)} self.module_framework.set_image_ordering(lambda x: img_ordering[x]) self.posted_images_set.add(tag) self.module_framework.write_image(tag, image, min(acq_times)) self.should_reload = False main_thread = threading.Thread(target=func) register_exit_signals(sigh) main_thread.start() main_thread.join() cleanup() if self.should_reload: aph.reload_self()
def __init__(self): self.init = False self.gladefile = os.path.join(__location__, "gui/cave.glade") self.builder = Gtk.Builder() self.builder.add_from_file(self.gladefile) # Automatically connect signals to functions defined above self.builder.connect_signals(self) #Set up the video tree self.video_tree = self.builder.get_object("videoTreeView") self.video_tree_manager = VideoTreeManager(self.video_tree, self) #Set up the filter box self.filter_box = self.builder.get_object("filterEntry") #Create & link video display widget self.video_box_container = self.builder.get_object("videoBox") self.video_box = VideoBox(self) self.video_box.show() self.video_box_container.pack_start(self.video_box, True, True, 0) #Create & Link timeline widget self.timeline_box = self.builder.get_object("timelineBox") self.timeline = Timeline(self) self.timeline.show() self.timeline_box.pack_start(self.timeline, True, True, 0) self.timeline.cursor_change = self._change_frame #Register listener self.video_box.length_listener = self.timeline.set_length #Register listener #Log playback filter_file = os.path.expanduser(args.filter) if args.filter else '' self.logplayer = LogPlayer(filter=filter_file) # Get the main window self.window = self.builder.get_object("caveWindow") self.window.show() #Initialize gtk's thread engine; add any threads after these lines Gdk.threads_init() GLib.threads_init() #Start video player thread self.video_player = VideoPlayer(self) self.play_button = self.builder.get_object("playButton") # Used to ignore program play button toggling. self.manual_play_reset = False self.enable_button = self.builder.get_object("enableButton") self.toggle_all_button = self.builder.get_object("toggleAllButton") #Start video rendering thread self.video_box.start_thread() #Start video preview manager self.video_preview_manager = VideoPreviewManager( self.video_box.vmt) #link w/ video manager thread self.video_preview_manager.register_callback( self.timeline.preview_callback) self.timeline.set_preview_manager(self.video_preview_manager) #Create statusbar display thread self.statusbar = StatusBarManager(self.builder.get_object("statusBar")) self.statusbar.display("Welcome to CAVE!", 2) self.db = None self.loop_button = self.builder.get_object("loopButton") #Load database file from arguments if present if args.database: self.load_db(args.database) elif os.path.exists(os.path.expanduser(self.config_file)): #Config File f = open(os.path.expanduser(self.config_file), "r") self.load_db(f.read()) else: vision_test_path = 'VISION_TEST_PATH' if vision_test_path in os.environ: #Search for databases in $VISION_TEST_PATH test_path = os.path.expandvars( os.path.expanduser(os.environ[vision_test_path])) for f in os.listdir(test_path): fname = os.path.join(test_path, f) if os.path.isfile(fname) and fname.endswith('.cdb'): self.load_db(fname) break #Ctrl+C handling def handler(signum, frame): self.log.warning("INTERRUPT; stopping CAVE") self.window_destroy(None) register_exit_signals(handler) #This fairly pointless function is necessary to periodically wake up #the gtk main thread to detect system interrupts even when not focused #I believe this is due to a Gtk bug GLib.timeout_add(500, lambda: True) #Make the window more shrinkable self.window.set_size_request(400, 400) #Fire up the main window self.log.info("Launching GUI. Welcome to CAVE!") self.init = True Gdk.threads_enter() Gtk.main() Gdk.threads_leave()
] @classmethod def run_test(cls): for act in cls.actuators: print("Firing %s..." % act) fire_actuators([act]) time.sleep(0.8) cls.cleanup() @classmethod def cleanup(cls): set_names_off(cls.actuators) if __name__ == "__main__": def interrupt(signal, frame): ActuatorTest.cleanup() sys.exit(0) register_exit_signals(interrupt) print("ATTENTION: This will fire both torpedos and markers!") print("\tBe sure that grabbers have not been reassigned") print("\tPress ENTER to continue or Control-C to quit") input() ActuatorTest.run_test()