示例#1
0
    def __init__(self, meta=None, events=None):

        self.event = curio.UniversalQueue()

        self.piglet_event = curio.UniversalQueue()

        self.piglets = curio.UniversalQueue()

        self.builds = curio.UniversalQueue()

        self.widgets = deque()
        self.current = None
        self.eric = None

        self.create_event_map()

        from karmapi import piglet

        # this probably needs to be a co-routine?
        self.eloop = piglet.EventLoop()
        self.eloop.set_event_queue(self.event)

        self.piglets.put(self.eloop.run())

        self.micks = curio.UniversalQueue()
示例#2
0
 def __init__(self, pvdb, interfaces=None):
     super().__init__(pvdb, interfaces)
     self._task_group = None
     # _stop_queue is used like a threading.Event, allowing a thread to stop
     # the Context in :meth:`.stop`.
     self._stop_queue = curio.UniversalQueue()
     self.command_bundle_queue = curio.Queue()
     self.subscription_queue = curio.UniversalQueue()
示例#3
0
    def __init__(self,
                 processor,
                 sample_iter,
                 echo=None,
                 broadcast_socket=None):
        """Manages advancing through a concrete FileProcessor
        subblass asynchronously. The processor pushes Interval
        updates on to the `worker_q`, which are also forwarded
        to an `events_q`. Additional async tasks can subscribe to 
        either queue; the `events_q` is considered the outward-facing
        point.

        `sample_iter` should be conform to that produced by
        `goetia.processing.iter_fastx_inputs`.
        
        Args:
            processor (libgoetia.InserterProcessor<T>): Processor to manage.
            sample_iter (iterator): Iterator over pairs of or single samples.
            echo (bool): Whether to echo `events_q` to the terminal.
            broadcast_socket (str, optional): AF_UNIX socket to broadcast
                the events queue on.
        """

        self.worker_q = curio.UniversalQueue()
        self.worker_subs = QueueManager(self.worker_q, 'worker_q')

        self.events_q = curio.UniversalQueue()
        self.events_subs = QueueManager(self.events_q, 'events_q')

        self.channels = OrderedDict()
        self.channels[self.worker_subs.name] = self.worker_subs
        self.channels[self.events_subs.name] = self.events_subs

        # We want everything from the worker q to also end
        # up on the events q
        self.subscribe('worker_q', self.events_q, 'events_q')

        self.listener_tasks = []

        self.processor = processor
        self.sample_iter = sample_iter

        self.run_echo = echo is not None
        self.echo_file = '/dev/stderr' if echo is True else echo

        self.state = RunState.READY
        self.processed = set()

        self.seconds_elapsed = 0
示例#4
0
async def mainloop():

    msg_queue = curio.UniversalQueue()
    quit_event = curio.UniversalEvent()

    parent = "NextTarget"
    uploader = FailSafeUploader(msg_queue, quit_event, get_firebase_default)
    uploader_thread = threading.Thread(target=uploader.upload, args=(parent, ))

    uploader_thread.start()

    zmqloop = await curio.spawn(loop_zmq(msg_queue))

    goodbye = curio.SignalEvent(signal.SIGINT, signal.SIGTERM)
    await goodbye.wait()

    print("stopping fb uploader")

    await quit_event.set()
    await msg_queue.put(dict(_task="quit"))

    await curio.run_in_thread(uploader_thread.join)

    try:
        await zmqloop.cancel()

    except:
        import traceback
        traceback.print_exc()
示例#5
0
    def __init__(self, app=None):

        if app is None:
            self.app = Tk()

        self.events = curio.UniversalQueue()
        self.app.bind('<Key>', self.keypress)
示例#6
0
def threaded_in_curio_wrapper(fcn):
    '''Run a threaded test with curio support

    Usage
    -----
    Wrap the threaded function using this wrapper, call the wrapped function
    using `curio.run_in_thread` and then await wrapped_function.wait() inside
    the test kernel.
    '''
    uqueue = curio.UniversalQueue()

    @functools.wraps(fcn)
    def wrapped():
        try:
            fcn()
        except Exception as ex:
            uqueue.put(ex)
        else:
            uqueue.put(None)

    async def wait():
        'Wait for the test function completion'
        res = await uqueue.get()
        if res is not None:
            raise res

    wrapped.wait = wait
    return wrapped
示例#7
0
def threaded_in_curio_wrapper(fcn):
    '''Run a threaded test with curio support

    Usage
    -----
    Wrap the threaded function using this wrapper, call the wrapped function
    using `curio.run_in_thread` and then await wrapped_function.wait() inside
    the test kernel.
    '''
    # Hide this import so that the other fixtures are usable by other
    # libraries (e.g. ophyd) without the experimental dependencies.
    import curio
    uqueue = curio.UniversalQueue()

    def wrapped_threaded_func():
        try:
            fcn()
        except Exception as ex:
            uqueue.put(ex)
        else:
            uqueue.put(None)

    @functools.wraps(fcn)
    async def test_runner():
        'Wait for the test function completion'
        await curio.run_in_thread(wrapped_threaded_func)
        res = await uqueue.get()
        if res is not None:
            raise res

    return test_runner
示例#8
0
async def main():
    q = curio.UniversalQueue()
    prod_task = threading.Thread(target=producer, args=(q, ))
    prod_task.start()
    cons_task = await curio.spawn(consumer, q)
    await curio.run_in_thread(prod_task.join)
    await cons_task.cancel()
示例#9
0
 def __init__(self, game_state_store: GameStateStore):
     logger.debug("Creating GameStateMachine instance.")
     self.game_time: float = 0.0
     self._event_queue = curio.UniversalQueue()
     self._universal_event_handler = UniversalEventHandler()
     self._game_state_store = game_state_store
     self._game_loop_is_running = False
示例#10
0
    def __init__(self, url: str) -> None:
        super().__init__(url)

        #: The gateway task running in an async thread.
        self._task = None  # type: curio.Task

        self._queue = curio.UniversalQueue()
        self._cancelled = threading.Event()
        self._ws = None  # type: WebSocket
示例#11
0
    def __init__(self, mick = None, *args, **kwargs):
        """ Fixme: configure stream according to **kwargs """

        if mick is None:
            self.mick = get_stream()
        else:
            self.mick = mick

        self.queue = curio.UniversalQueue(maxsize=2)
示例#12
0
    def __init__(self, *args, **kwargs):

        self.keymap = self.keymap_karma.copy()

        print('core pig creating self.event_queue')
        self.event_queue = curio.UniversalQueue()

        print('Creating Pig with event queue', self.event_queue)

        self.event_map = {}
示例#13
0
 def __init__(self,
              devices: Sequence[gpiozero.AnalogInputDevice],
              device_names: Sequence[str],
              block_length: float = 0.1,
              tick: float = 0.01,
              max_qsize: int = 10000):
     self.devices = devices
     self.device_names = device_names
     self.block_length = block_length
     self.tick = tick
     self.output = curio.UniversalQueue(maxsize=max_qsize)
     self.running = False
示例#14
0
 def __init__(self, remote_address: tuple, event_handler, event_wire=None):
     logger.debug(
         f"Creating connection instance for remote address {remote_address}."
     )
     self.remote_address = remote_address
     self.event_handler = event_handler
     self.event_wire = event_wire
     self.local_sequence = Sqn(0)
     self.remote_sequence = Sqn(0)
     self.ack_bitfield = "0" * 32
     self.latency = 0.0
     self.status = ConnectionStatus.get("Disconnected")
     self.quality = "good"  # this is used for congestion avoidance
     self._package_interval = self._package_intervals["good"]
     self._outgoing_event_queue = curio.UniversalQueue()
     self._incoming_event_queue = curio.UniversalQueue()
     self._pending_acks: dict = {}
     self._event_callback_sequence = Sqn(0)
     self._events_with_callbacks: dict = {}
     self._event_callbacks: dict = {}
     self._last_recv = time.time()
示例#15
0
    def __init__(self):
        self.root = Tk()
        self.root.alt_shortcuts = set()
        self.model = Model()
        self.view = View(self.root, self.model)
        self.root.title("McRoss Browser")
        self.root.geometry("800x600")

        self.gui_ops = curio.UniversalQueue(withfd=True)
        self.coro_ops = curio.UniversalQueue()

        # When in the middle of an action, this flag is set to False to prevent user
        # from clicking other random stuff:
        self.allow_user_interaction = True

        def put_coro_op(func):
            def inner(*args):
                if self.allow_user_interaction:
                    self.coro_ops.put(self.show_waiting_cursor_during_task(func, *args))

            return inner

        # Make sure queued GUI operations are executed as soon as they become available
        if hasattr(self.root, "createfilehandler"):
            self.root.createfilehandler(self.gui_ops, READABLE, self.process_gui_ops)
        else:
            print("Running poll-based workaround for Windows.")
            # This is way more inefficient (5% CPU usage on a Surface Go at idle) but
            # hey it's better than not working at all!

            def after_cb():
                self.process_gui_ops()
                self.root.after(10, after_cb)

            self.root.after(10, after_cb)

        self.view.go_callback = put_coro_op(self.go_callback)
        self.view.link_click_callback = put_coro_op(self.link_click_callback)
        self.view.back_callback = put_coro_op(self.back_callback)
        self.view.forward_callback = put_coro_op(self.forward_callback)
示例#16
0
    async def start(self) -> None:
        recv_task = await curio.spawn(self.recv_data)

        queue = curio.UniversalQueue()
        stdin_thread = Thread(target=read_peer_info, args=(queue,))
        stdin_thread.start()

        peer_ip, peer_port = await queue.get()
        print(f'Connecting to: {peer_ip}:{peer_port}')

        await self._sock.sendto(b'hey there!', (peer_ip, peer_port))

        stdin_thread.join()
        await recv_task.join()
示例#17
0
    def __init__(self, net, apply=None):
        # Some information about the network topology
        self.address = net.address
        self.net = net
        self.numservers = net.numservers
        self.quorum = (self.numservers // 2) + 1
        self.machine = RaftMachine(self, apply)
        self.events = curio.UniversalQueue()
        self._alive = False

        # Persistent log
        self._restore_log()
        self._plog = open(f'{self.address}-plog.p', 'ab')
        self._plog.seek(0, os.SEEK_END)
        
        # Debugging/Testing.
        self.paused = False
示例#18
0
文件: server.py 项目: ZLLentz/caproto
    def __init__(self, host, port, pvdb, *, log_level='ERROR'):
        self.host = host
        self.port = port
        self.pvdb = pvdb

        self.circuits = set()
        self.log_level = log_level
        self.broadcaster = ca.Broadcaster(our_role=ca.SERVER)
        self.broadcaster.log.setLevel(self.log_level)
        self.command_bundle_queue = curio.Queue()

        self.subscriptions = defaultdict(deque)
        self.subscription_queue = curio.UniversalQueue()
        self.beacon_count = 0
        self.environ = get_environment_variables()

        ignore_addresses = self.environ['EPICS_CAS_IGNORE_ADDR_LIST']
        self.ignore_addresses = ignore_addresses.split(' ')
示例#19
0
    async def start(self) -> None:
        queue = curio.UniversalQueue()
        stdin_thread = Thread(target=read_peer_info, args=(queue,))
        stdin_thread.start()

        peer_ip, peer_port = await queue.get()
        print(f'Connecting to: {peer_ip}:{peer_port}')

        await self._sock.connect((peer_ip, peer_port))
        # We must start reading only when connected, otherwise Linux returns
        # socket error #107
        recv_task = await curio.spawn(self.recv_data)

        print('Connected')
        await self._sock.send(b'hey there!')
        print('Sent msg')

        stdin_thread.join()
        await recv_task.join()
示例#20
0
    def __init__(self, mode = None, scale=50, *args, **kwargs):
        """ Fixme: configure stream according to **kwargs """

        self.queue = curio.UniversalQueue(maxsize=2)

        n = 2 * CHUNK

        if mode == 'square':
            frames = int(n / 32)
            plus = [3000] * 16
            minus = [-3000] * 16
            data = (plus + minus) * frames
        else:
            data = np.arange(n)
            data = np.sin(data * math.pi / 50.0) * (2**15 - 1)

        print('xxxxxxxxxxxxxxxxx', mode, len(data))

        self.data = data
示例#21
0
    def __init__(self):
        # Need to start an event loop
        self.in_queue = curio.UniversalQueue()  # Incoming message queue
        self.out_queue = curio.UniversalQueue()  # Outgoing message queue

        self.devices = []
示例#22
0
 def __init__(self, pvdb, interfaces=None):
     super().__init__(pvdb, interfaces)
     self.command_bundle_queue = curio.Queue()
     self.subscription_queue = curio.UniversalQueue()
示例#23
0
                                  '%(levelname)s - %(message)s')

    ch.setFormatter(formatter)

    logger.addHandler(ch)

    return logger


logger = get_logger()

watchdir_queue = curio.Queue()
# files_created_queue = curio.Queue()

# to communicate with FB thread
msg_queue = curio.UniversalQueue()
quit_event = curio.UniversalEvent()


async def watcher_spawner():
    async with curio.TaskGroup() as tg:
        async for watchdir in watchdir_queue:
            await tg.spawn(watch_continously(watchdir))
            # tasks.append(t)


def create_msg(root, filename):
    _postfix = "_tan.nh.phot.cat"
    if not filename.endswith(_postfix):
        return None
示例#24
0
 def __init__(self, locals):
     super().__init__(locals)
     self.compile.compiler.flags |= ast.PyCF_ALLOW_TOP_LEVEL_AWAIT
     self.requests = curio.UniversalQueue()
     self.response = curio.UniversalQueue()
示例#25
0
 def __init__(self, pvdb, interfaces=None):
     super().__init__(pvdb, interfaces)
     self._task_group = None
     self._stop_event = threading.Event()
     self.command_bundle_queue = curio.Queue()
     self.subscription_queue = curio.UniversalQueue()
示例#26
0
 def __init__(self, remote_address: tuple, event_handler):
     super().__init__(remote_address, event_handler)
     self._command_queue = curio.UniversalQueue()
     self.game_state_context = LockedRessource(GameState())