Ejemplo n.º 1
0
    def test_handler(self):
        @count_calls
        def interrupt_polling():
            print('Caught CTRL-C!')

        if os.name == 'nt':
            from ctypes import windll
            from ctypes.wintypes import BOOL, DWORD

            kernel32 = windll.LoadLibrary('kernel32')

            # <http://msdn.microsoft.com/en-us/library/ms683155.aspx>
            GenerateConsoleCtrlEvent = kernel32.GenerateConsoleCtrlEvent
            GenerateConsoleCtrlEvent.argtypes = (DWORD, DWORD)
            GenerateConsoleCtrlEvent.restype = BOOL

            try:
                # Simulate CTRL-C event while handler is active.
                with allow_interrupt(interrupt_polling):
                    result = GenerateConsoleCtrlEvent(0, 0)
                    if result == 0:
                        raise WindowsError
            except KeyboardInterrupt:
                pass
            else:
                self.fail('Expecting `KeyboardInterrupt` exception!')

            # Make sure our handler was called.
            self.assertEqual(interrupt_polling.__calls__, 1)
        else:
            # On non-Windows systems, this utility is just a no-op!
            with allow_interrupt(interrupt_polling):
                pass
            self.assertEqual(interrupt_polling.__calls__, 0)
Ejemplo n.º 2
0
    def test_handler(self):
        @count_calls
        def interrupt_polling():
            print('Caught CTRL-C!')

        if os.name == 'nt':
            from ctypes import windll
            from ctypes.wintypes import BOOL, DWORD

            kernel32 = windll.LoadLibrary('kernel32')

            # <http://msdn.microsoft.com/en-us/library/ms683155.aspx>
            GenerateConsoleCtrlEvent = kernel32.GenerateConsoleCtrlEvent
            GenerateConsoleCtrlEvent.argtypes = (DWORD, DWORD)
            GenerateConsoleCtrlEvent.restype = BOOL

            try:
                # Simulate CTRL-C event while handler is active.
                with allow_interrupt(interrupt_polling):
                    result = GenerateConsoleCtrlEvent(0, 0)
                    if result == 0:
                        raise WindowsError
            except KeyboardInterrupt:
                pass
            else:
                self.fail('Expecting `KeyboardInterrupt` exception!')

            # Make sure our handler was called.
            self.assertEqual(interrupt_polling.__calls__, 1)
        else:
            # On non-Windows systems, this utility is just a no-op!
            with allow_interrupt(interrupt_polling):
                pass
            self.assertEqual(interrupt_polling.__calls__, 0)
Ejemplo n.º 3
0
def main(addrs):
    context = zmq.Context()
    control = context.socket(zmq.PUB)
    control.bind('inproc://control')
    updates = context.socket(zmq.SUB)
    updates.setsockopt(zmq.SUBSCRIBE, "")
    updates.connect('inproc://control')
    for addr in addrs:
        print("Connecting to: ", addr)
        updates.connect(addr)

    def interrupt_polling():
        """Fix CTRL-C on Windows using "self pipe trick"."""
        control.send_multipart(['', 'quit'])

    with allow_interrupt(interrupt_polling):
        message = ''
        while message != 'quit':
            message = updates.recv_multipart()
            if len(message) < 2:
                print('Invalid message.')
                continue
            account = message[0]
            message = ' '.join(message[1:])
            if message == 'quit':
                print('Killed by "%s".' % account)
                break
            print('%s: %s' % (account, message))
Ejemplo n.º 4
0
def main(addrs):
    context = zmq.Context()
    control = context.socket(zmq.PUB)
    control.bind('inproc://control')
    updates = context.socket(zmq.SUB)
    updates.setsockopt(zmq.SUBSCRIBE, "")
    updates.connect('inproc://control')
    for addr in addrs:
        print("Connecting to: ", addr)
        updates.connect(addr)

    def interrupt_polling():
        """Fix CTRL-C on Windows using "self pipe trick"."""
        control.send_multipart(['', 'quit'])

    with allow_interrupt(interrupt_polling):
        message = ''
        while message != 'quit':
            message = updates.recv_multipart()
            if len(message) < 2:
                print('Invalid message.')
                continue
            account = message[0]
            message = ' '.join(message[1:])
            if message == 'quit':
                print('Killed by "%s".' % account)
                break
            print('%s: %s' % (account, message))
Ejemplo n.º 5
0
    def test_handler(self):
        @count_calls
        def interrupt_polling():
            print('Caught CTRL-C!')

        from ctypes import windll
        from ctypes.wintypes import BOOL, DWORD

        kernel32 = windll.LoadLibrary('kernel32')

        # <http://msdn.microsoft.com/en-us/library/ms683155.aspx>
        GenerateConsoleCtrlEvent = kernel32.GenerateConsoleCtrlEvent
        GenerateConsoleCtrlEvent.argtypes = (DWORD, DWORD)
        GenerateConsoleCtrlEvent.restype = BOOL

        # Simulate CTRL-C event while handler is active.
        try:
            with allow_interrupt(interrupt_polling) as context:
                result = GenerateConsoleCtrlEvent(0, 0)
                # Sleep so that we give time to the handler to
                # capture the Ctrl-C event.
                time.sleep(0.5)
        except KeyboardInterrupt:
            pass
        else:
            if result == 0:
                raise WindowsError()
            else:
                self.fail('Expecting `KeyboardInterrupt` exception!')

        # Make sure our handler was called.
        self.assertEqual(interrupt_polling.__calls__, 1)
Ejemplo n.º 6
0
def main_phidget():
    import threading

    from zmq.utils.win32 import allow_interrupt
    from flyvr.common.build_arg_parser import build_argparser, parse_options

    parser = build_argparser()
    parser.add_argument(
        "--debug_led",
        type=int,
        help="flash this LED upon IPC messages (should not be 3,4,5)",
        default=None)

    options = parse_options(parser.parse_args(), parser)

    # silly little dance to make ZMQ blocking read ctrl-c killable by running the entire
    # thing in a thread and waiting on an event instead

    quit_evt = threading.Event()

    def ctrlc(*args):
        quit_evt.set()

    t = threading.Thread(target=run_phidget_io, args=(options, ), daemon=True)
    t.start()

    with allow_interrupt(action=ctrlc):
        try:
            quit_evt.wait()
        except KeyboardInterrupt:
            pass
Ejemplo n.º 7
0
def run(args):
    import colorama
    colorama.init()

    sockets = connect_sockets(args.address)

    abort_push = zmq.Context.instance().socket(zmq.PAIR)
    abort_push.bind('inproc://sail_monitor/abort')
    abort_pull = zmq.Context.instance().socket(zmq.PAIR)
    abort_pull.connect('inproc://sail_monitor/abort')

    already_received = set()

    def abort():
        abort_push.send('ABORT')

    with allow_interrupt(abort):
        while True:
            (read, _, _) = zmq.select(sockets + [abort_pull], [], [])

            if abort_pull is read:
                break

            for ready in read:
                frame = ready.recv()
                frame = parse_frame(frame)
                process_frame(already_received, frame)
Ejemplo n.º 8
0
    def test_handler(self):
        @count_calls
        def interrupt_polling():
            print('Caught CTRL-C!')

        from ctypes import windll
        from ctypes.wintypes import BOOL, DWORD

        kernel32 = windll.LoadLibrary('kernel32')

        # <http://msdn.microsoft.com/en-us/library/ms683155.aspx>
        GenerateConsoleCtrlEvent = kernel32.GenerateConsoleCtrlEvent
        GenerateConsoleCtrlEvent.argtypes = (DWORD, DWORD)
        GenerateConsoleCtrlEvent.restype = BOOL

        # Simulate CTRL-C event while handler is active.
        try:
            with allow_interrupt(interrupt_polling) as context:
                result = GenerateConsoleCtrlEvent(0, 0)
                # Sleep so that we give time to the handler to
                # capture the Ctrl-C event.
                time.sleep(0.5)
        except KeyboardInterrupt:
            pass
        else:
            if result == 0:
                raise WindowsError()
            else:
                self.fail('Expecting `KeyboardInterrupt` exception!')

        # Make sure our handler was called.
        self.assertEqual(interrupt_polling.__calls__, 1)
Ejemplo n.º 9
0
def main_sound_server():
    import yaml
    import os.path

    from flyvr.common.build_arg_parser import build_argparser, parse_options
    from flyvr.audio.util import plot_playlist
    from zmq.utils.win32 import allow_interrupt

    parser = build_argparser()
    parser.add_argument('--print-devices',
                        action='store_true',
                        help='print available audio devices')
    parser.add_argument('--convert-playlist',
                        help='convert a stimulus playlist to new format')
    parser.add_argument('--paused', action='store_true', help='start paused')
    parser.add_argument('--plot',
                        action='store_true',
                        help='plot the stimulus playlist')

    options = parse_options(parser.parse_args(), parser)

    if options.plot:
        setup_logging(options)

        if not options.playlist.get('audio'):
            return parser.error('Config file contains no audio playlist')

        plot_playlist(options, 'audio')

        return parser.exit(0)

    if options.convert_playlist:
        src = options.convert_playlist
        if os.path.isfile(src):
            pl = AudioStimPlaylist.from_legacy_filename(src)
            dest = options.convert_playlist + '.yml'
            with open(dest, 'wt') as f:
                yaml.dump({'playlist': {'audio': pl.describe()}}, f)

            return parser.exit(0, message='Wrote %s' % dest)

        else:
            return parser.error('Could not find %s' % src)

    if options.print_devices:
        SoundServer.list_supported_asio_output_devices()
        return parser.exit(0)

    quit_evt = threading.Event()

    # noinspection PyUnusedLocal
    def ctrlc(*args):
        quit_evt.set()

    with allow_interrupt(action=ctrlc):
        run_sound_server(options, quit_evt)
Ejemplo n.º 10
0
    def run(self):
        self.context = SecureContext.instance(shared_secret=self.shared_secret)
        self.router = self.context.socket(
            zmq.ROUTER, allow_insecure=self.allow_insecure
        )
        self.stop_sock = self.context.socket(zmq.PULL)
        self.poller = zmq.Poller()
        self.poller.register(self.router, zmq.POLLIN)
        self.poller.register(self.stop_sock, zmq.POLLIN)
        if self.port is not None:
            self.router.bind('%s:%d' % (self.bind_address, self.port))
        else:
            self.port = self.router.bind_to_random_port(self.bind_address)
        self.shutdown_endpoint = 'inproc://zpself' + hexlify(os.urandom(8)).decode()
        self.stop_sock.bind(self.shutdown_endpoint)

        global logger
        logger = setup_logging('zlock', self.silent, self.server_log_dir)
        if not self.silent:
            # Log insecure connection attempts:
            self.router.logger = logger
        msg = 'This is zlock server, running on %s:%d'
        logger.info(msg, self.bind_address, self.port)
        self.running = True
        self.started.set()
        try:
            with allow_interrupt(self._win32_keyboardinterrupt):
                try:
                    self._mainloop()
                except KeyboardInterrupt:
                    # An organic keyboard interrupt on mac or linux:
                    self.stop()
                    raise
            if self._interrupted:
                # A hacky windows keyboard interrupt. stop() has already been called.
                raise KeyboardInterrupt
        finally:
            self.router.close()
            self.router = None
            self.stop_sock.close()
            self.stop_sock = None
            self.context = None
            self.port = self._initial_port
            self.shutdown_endpoint = None
            self.running = False
            self.started.clear()
            self._interrupted = False
Ejemplo n.º 11
0
    def run(self):
        self.listening_sockets = self.connect_sockets(self.endpoints)

        try:
            self.command_socket.bind('tcp://0.0.0.0:{}'.format(self.port))
            self.command_bound = True
        except:
            print("Can't bind to port {}".format(self.port))

        tasklist = self.load_tasklist(self.mission_path, self.session)
        original_tasklist_length = len(tasklist)
        print("Loaded {} tasks.".format(original_tasklist_length))
        self.download_tasks = self.create_dictionary(tasklist)

        if original_tasklist_length == 0:
            return

        self.ui = MonitorUI(self.session, self.download_tasks,
                            original_tasklist_length, self.abort,
                            self.command_bound)
        ui_thread = self.ui.run()

        with allow_interrupt(self.abort):
            while True:
                try:
                    (read, _, _) = zmq.select(
                        self.listening_sockets + [self.abort_pull] +
                        [self.command_socket], [], [])
                except KeyboardInterrupt:
                    self.ui.log("Ending...")
                    break

                if self.abort_pull in read:
                    break

                if self.command_socket in read:
                    self.handle_commands(self.command_socket.recv())
                    continue

                for ready in read:
                    frame = ready.recv()
                    frame = self.parse_frame(frame)
                    self.process_frame(frame)

        self.ui.stop()
        ui_thread.join()
Ejemplo n.º 12
0
def main():
    # with ServerProxy("http://127.0.0.1:8000/", verbose=False, allow_none=True) as proxy:
    if True:
        pass

    #D:\Devel\github\keras-rl;D:\Devel\github\Devel\hz-b\naus
    # set PYTHONPATH=D:\Devel\github\keras-rl;D:\Devel\github\Devel\hz-b\naus
    # & python d:\Devel\github\Devel\hz-b\naus\examples\rl\cart_pole\sarsa_cartpole.py

    def stop_my_application():
        print('Stopping application')

    with allow_interrupt():
        # main polling loop.

        env = EnvironmentProxyForClient(receiver=None)
        np.random.seed(1974)
        env.seed(1974)

        env.reset()

        # nb_actions = cpst._action_space
        nb_actions = 2
        # Next, we build a very simple model.
        model = Sequential()
        #n_os = cpst._observation_space.shape

        n_os = 4
        model.add(Flatten(input_shape=[1] +[n_os]))
        model.add(Dense(16))
        model.add(Activation('relu'))
        model.add(Dense(16))
        model.add(Activation('relu'))
        model.add(Dense(16))
        model.add(Activation('relu'))
        model.add(Dense(nb_actions))
        model.add(Activation('linear'))
        print(model.summary())

        # SARSA does not require a memory.
        policy = BoltzmannQPolicy()
        sarsa = SARSAAgent(model=model, nb_actions=nb_actions, nb_steps_warmup=10, policy=policy)
        sarsa.compile(Adam(lr=1e-3), metrics=['mae'])

        run_test(sarsa, env, log=log)
Ejemplo n.º 13
0
    def receive(self):
        while self.receive_no_wait() is not None:
            pass

        def stop():
            self.abort_send.send('QUIT')

        self._flush_socket(self.abort_recv, -1)

        with allow_interrupt(stop):
            (read, _, _) = zmq.select([self.sock, self.abort_recv], [],
                                      [self.sock, self.abort_recv])

            if read[0] == self.sock:
                return self.sock.recv()
            elif read[0] == self.abort_recv:
                return None
            else:
                return None
Ejemplo n.º 14
0
def run(args):
    colorama.init()

    sockets = connect_sockets(args.address)

    abort_push = zmq.Context.instance().socket(zmq.PAIR)
    abort_push.bind('inproc://sail_monitor/abort')
    abort_pull = zmq.Context.instance().socket(zmq.PAIR)
    abort_pull.connect('inproc://sail_monitor/abort')

    def abort():
        abort_push.send('ABORT')

    counter = 1

    with allow_interrupt(abort):
        with tableprint.TableContext([
                'Time', 'GS', 'BitRate', 'BP VOLT', 'BP TEMP',
                'COMM RX Current', '3V3 DISTR CURRENT'
        ],
                                     width=20,
                                     style='grid') as tc:
            while True:
                (read, _, _) = zmq.select(sockets.keys() + [abort_pull], [],
                                          [])

                if abort_pull is read:
                    break

                for ready in read:
                    gs = sockets[ready]
                    frame = ready.recv()
                    frame = parse_frame(frame)

                    if not isinstance(frame, response_frames.BeaconFrame):
                        continue

                    if counter % 10 == 0:
                        print(tc.headers)

                    counter += 1

                    process_frame(gs, tc, frame)
Ejemplo n.º 15
0
def main_relay():
    # zmq blocking calls eat ctrl+c on windows, which means this command line entry is
    # not ctrl+c killable. To make it so, run it instead in a daemon thread and use a zmq interrupt
    # override to let us catch the ctrl+c and break out of the indefinite wait on the quit event

    # noinspection PyPackageRequirements
    from zmq.utils.win32 import allow_interrupt

    quit_evt = threading.Event()

    # noinspection PyUnusedLocal
    def ctrlc(*args):
        quit_evt.set()

    t = threading.Thread(target=run_main_relay, daemon=True)
    t.start()

    with allow_interrupt(action=ctrlc):
        try:
            quit_evt.wait()
        except KeyboardInterrupt:
            pass